Circe is a JSON library for
Scala which built based on Argonaut and Cats. It provides compile-time derived codecs for encode/decode JSON into case classes. Circe library can be used as an alternative for
spray-json in various scenarios. For an example
http4s a type safe, functional, HTTP streaming library using circe as the default JSON library.
In this post I’m gonna discuss various JSON encode/decode operation that can be performed with circe. All the source code which related to this post available on gitlab. Please clone the repo and follow the post.
IntelliJ Idea as my IDE to work with Scala applications. I need to create
sbt project and add the
build.sbt dependency file with
circe and other dependencies. Following is the
build.sbt dependency file.
parser.decode functions to encode and decode simple case class objects. It automatically handles option fields. If options field does not exists when decoding, it identifies the field as a
Nested objects can automatically encode/decode with
parser.decode functions in circe.
List objects can automatically encode/decode with
parser.decode function in circe.
We can read/write custom JSON objects by defining custom
Decoder with circe.
Enumeratum is a type-safe enumeration implementation for Scala. We can define enums with
Enumeratum and encode/decode them using
Another common way of defining enums in scala is with
sealed traits. To encode/decode sealed trait based enums we can use
Instead of decoding the whole JSON object, circe can extract specific field by traversing through the JSON.