Hacking with scala circe-json

Happy devOps

λ.eranga
λ.eranga
Oct 23 · 2 min read

About Circe

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.

Sbt dependency

I’m using 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.

Simple objects

Circe provides asJson and 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 None.

Nested objects

Nested objects can automatically encode/decode with asJson and parser.decode functions in circe.

List objects

List objects can automatically encode/decode with asJson and parser.decode function in circe.

Custom encode/decode

We can read/write custom JSON objects by defining custom Encoder and Decoder with circe.

Handle enums

Enumeratum is a type-safe enumeration implementation for Scala. We can define enums with Enumeratum and encode/decode them using enumeratum-circe package.

Another common way of defining enums in scala is with sealed traits. To encode/decode sealed trait based enums we can use circe-generic-extras package.

Traversing JSON

Instead of decoding the whole JSON object, circe can extract specific field by traversing through the JSON.

Reference

  1. https://beachape.com/blog/2016/04/16/enumeratum-1-dot-4-valueenums-plus-circe/
  2. https://github.com/circe/circe/issues/1203
  3. https://dzone.com/articles/5-useful-circe-feature-you-may-have-overlooked
  4. https://medium.com/@djoepramono/how-to-parse-json-in-scala-c024cb44f66b
  5. https://circe.github.io/circe/optics.html
  6. https://immutables.pl/2017/02/25/customizing-circes-auto-generic-derivation/

λ.eranga

Written by

λ.eranga

Scala, Golang with Vim and Hockey: What else does a man need to be happy :)

Rahasak

Rahasak

Have less, be more

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade