Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

5 Useful circe Features You May Have Overlooked

DZone's Guide to

5 Useful circe Features You May Have Overlooked

circe is a library that provides a fully functional approach to JSON processing. Read on to see some of its most helpful features.

Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

If you are using Scala and need to do some JSON processing, circe is one of the best options available. It utilizes fully functional approach and lets you work with JSON without any boilerplate and runtime reflection.

In this blog post, I will show some of the most useful features of this library that often get overlooked, and hopefully, this can save you a lot of development time and effort.

Before proceeding, we need to add the following dependencies to the build.sbt:

libraryDependencies ++= Seq(
  "io.circe" %% "circe-core" % "0.8.0",
  "io.circe" %% "circe-generic" % "0.8.0",
  "io.circe" %% "circe-parser" % "0.8.0",
  "io.circe" %%"circe-literal" % "0.8.0",
)

JSON Literal

JSON literal allows you to construct sample JSON objects in the code using inline syntax. This feature is located in the circe-literal module, and you need to import the import io.circe.literal._ package to be able to use it. Here is an example:

import io.circe.literal._

val myJson: io.circe.Json =
json"""{
 "name": "value",
 "list": [1,2,3]
    } """

It looks like a regular multiline string, but actually, the content of it is being validated in the compile time; if you miss a comma or a quote it won’t compile.

This is a really handy feature because the alternative approaches are either cumbersome to use (composing various io.circe.Json methods/objects) or don’t check your JSON correctness at compile time (io.circe.parser.parse returns Either[Json, ParsingFailure]).

Snake Case

This issue arises when you need to work with JSON in snake case but have your model in Scala defined as a bunch of cases classes with fields in camel case (as the Scala style guide suggests).

One way to handle it is to change the field names of your model classes to snake case. Or you can list the field names explicitly with forProductN(...) helpers when defining encoders/decoders.

  implicit val encoder: Encoder[Event] =
    Encoder.forProduct3("event_id", "event_name", "status")(Event.unapply(_).get)
  implicit val decoder: Decoder[Event] =
    Decoder.forProduct3("event_id", "event_name", "status")(Event.apply)

This works, but it quickly gets tedious. Imagine a case class with 20 fields, and every time something changes (even the field order), you have to keep it up-to-date.

Another way is to chain your encoders/decoders with encoder.mapJsonObject()or decoder.prepare() to prepare the JSON to fit the model, but the best approach, in my opinion, is to use the circe-derivation module.

It requires an additional dependency: libraryDependencies += "io.circe" %% "circe-derivation" % "0.8.0-M2",

And it looks pretty simple:

  import io.circe.derivation._
  import io.circe.{Decoder, Encoder, ObjectEncoder, derivation}

  implicit val decoder: Decoder[Event] = deriveDecoder(derivation.renaming.snakeCase)
  implicit val encoder: ObjectEncoder[Event] = deriveEncoder(derivation.renaming.snakeCase)

ADT

Many people prefer to use sealed traits to model enumerations in Scala:

sealed trait Priority
object Priority {
object Hi extends Priority
    object Medium extends Priority
    object Low extends Priority
}

But circe’s default way is to treat it polymorphically:

import io.circe.ObjectEncoder
import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}
import io.circe.syntax._

object Test extends App{
  case class Request(color: Priority)

  implicit val colorEncoder: = deriveEncoder[Priority]
  implicit val boxEncoder = deriveEncoder[Request]

  print(Box(Low).asJson.toString())
}

It is rendered as an object, but it is not what we intended.

{
  "color" : {
    "Low" : {

    }
  }
}

Luckily, it is easy to fix this in the generic-extras module:

libraryDependencies += "io.circe" %% "circe-generic-extras" % "0.9.0-M2"

Just change to

import io.circe.generic.extras.semiauto._
implicit val encoder = deriveEnumerationEncoder[Priority]

This time, the output looks as expected:

{
  "color" : "Blue"
}


Value Classes

There is a similar case with Value classes; they are also treated by circe as regular ones:

  case class UserId(id: Long) extends AnyVal

  implicit val encoder: Encoder[UserId] = deriveEncoder
  print(UserId(1L).asJson.toString())

Output:

{
  "id" : 1
}

But we know that conceptually, value classes are just syntactic sugar and they are represented as primitives on the by-code level, so it would make sense to treat them the same in JSON.

You can, of course, do something like this:

  // Extending AnyVal is mandatory for value classes
  case class UserId(id: Long) extends AnyVal

  implicit val incidentIdEncoder: Encoder[UserId] = Encoder.encodeLong.contramap(_.id)
  implicit val incidentIdDecoder: Decoder[UserId] = Decoder.decodeLong.map(UserId)

But one can make it more generic:

 import io.circe.generic.extras.semiauto._
 implicit val encoder: Encoder[UserId] = deriveUnwrappedEncoder
 implicit val decoder: Decoder[UserId] = deriveUnwrappedDecoder

Now it outputs just a raw value: 1

Decoders/Encoders for java.time.Instant

The last one is not exactly a feature, but a set of predefined encoders and decoders to help you to avoid reinventing the wheel. The circe-java8 module provides some useful encoders/decoders for Java’s time API, which includes classes like Instantand ZonedDateTime. Just mix in the TimeInstances trait and avoid the pain of defining all of it by hand.

You can find circe on GitHub.

With SnapLogic’s integration platform you can save millions of dollars, increase integrator productivity by 5X, and reduce integration time to value by 90%. Sign up for our risk-free 30-day trial!

Topics:
json ,scala ,integration

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}