DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Streamlining Event Data in Event-Driven Ansible
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality
  • Loading XML into MongoDB

Trending

  • Unlocking AI Coding Assistants Part 4: Generate Spring Boot Application
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Building Enterprise-Ready Landing Zones: Beyond the Initial Setup
  1. DZone
  2. Coding
  3. Languages
  4. 5 Useful circe Features You May Have Overlooked

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.

By 
Stanislav Chetvertkov user avatar
Stanislav Chetvertkov
·
Dec. 31, 17 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
29.2K Views

Join the DZone community and get the full member experience.

Join For Free

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.

JSON

Opinions expressed by DZone contributors are their own.

Related

  • Streamlining Event Data in Event-Driven Ansible
  • Dynamic Web Forms In React For Enterprise Platforms
  • Unlocking Oracle 23 AI's JSON Relational Duality
  • Loading XML into MongoDB

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!