My Scala JSON usage (2017)

By William "Scala William" Narmontas

Saturday, 18 February 2017

There are many JSON libraries for Scala, so which one do I choose?

I'll be talking about the following libraries that I used:

There are others as well, such as Argonaut and Upickle but I've not found the need to use them yet.

Each of them can be used in different situations and even combined.

A typical use case for JSON in Scala is to convert between a JSON object and a Scala case class, though there will be other use cases as well.

json4s: the oldie

json4s uses reflection to serialise your objects. This means rapid prototyping, but when you need power and customisation it'll fail you.

Offers the choice of a native Scala parser and a fasterxml-jackson backend.

Usage can be a bit confusing.

play-json: the workhorse

Well integrated with the Play Framework. Uses jackson underneath.

Uses Read/Write formats to serialise and deserialise your objects. They are generated via macros so it's more explicit than json4s.

Usage is very explicit and documentation is very good.

circe: the type-saviour

All the derivations are transparent and it uses the latest Scala techniques to derive Decoders and Encoders (ie play-json's Read/Write).

Documentation not totally up to scratch, Play's is better at the time of writing.

circe has a very bright future indeed. circe-yaml is out there as well.

rapture-json: unifying Scala JSON

rapture-json provides a wrapper layer around many of Scala's JSON libraries, and also comes with other nice pluses, such as JSON interpolation. This lets you write your JSON without intermediate case classes such as:

import rapture.json._
import rapture.json.jsonBackends.play._
val postBody: JsObject = json"""{
  "app_id": $appId,
  "ttl": 300,
  "template_id": "cebb4561-07d7-4b61-a0fd-3077c36f8e51",
  "included_segments": ["All"],
  "headings": {"en":${s"Inter @ ${validServer.name}, ${interOut.userMessage.nickname}"}},
  "url": ${s"https://actionfps.com/servers/?join=${addr}"}
}""".as[JsObject]

It even comes with mutable and immutable interfaces, so you don't have to be stuck in only one way of thinking!

You are not stuck in rapture's model either - it's very easy to move inbetween different models.

One unusual thing about rapture is that it provides different modes, such as throwing an exception - or returning an Either - or returning an Option, so you're never stuck in a single paradigm.

The documentation is not great to read and can be confusing.

jackson

jackson is a Java JSON library, one of the fastest, one of the best.

Typically you won't be using it but when you need the performance and power, consider it.

My usage / summary

play-json inside a Play app, circe outside of it. rapture-json when I want to enjoy do more fancy things.

json4s if I don't want to build custom encoders/decoders.

In the long run IMO circe will come out on top because of the heavy community backing.

Follow on Social Media