JSON is a widely used protocol for communication between services. Recently, I was tasked to write some serialization/deserialization logic in Scala, so I did a bit research and find json4s
to be an effective option for my use case. Here are some simple code snippets to get started with this library.
Basics
JSON AST is used to model the structure of a JSON document, which is the fundamental building block of json4s
.
1 | sealed abstract class JValue |
Features are implemented based on AST such as functions used to transform the AST itself, or between the AST and other formats.
Serialization
We can serialize Scala objects, such as case class
into JSON easily with json4s default formats.
1 | import org.json4s._ |
And, walla, you get what you want!
1 | { "id": 1, |
As you can see, the serialization is super easy for simple case classes and it supports the following out-of-box:
- Arbitrarily deep case class graphs
- All primitive types, including BigInt and Symbol
- List, Seq, Array, Set and Map (note, keys of the Map must be strings: Map[String, _])
- scala.Option
- java.util.Date
- Polymorphic Lists (see below)
- Recursive types
- Serialization of fields of a class
Of course, you might already started asking how about more complicated use cases. Luckily, json4s supports customized serialization logic as well with a little bit of extra work.
For illustration, let’s assume our Employee
case class is not serializable by default, we can plug in a customized serializer to achieve the same results.
1 | class EmployeeSerializer extends CustomSerializer[Employee] (format => |
The syntax is pretty straightforward to create a customized serializer and you can just plug it in as you would do with the default one.
Deserialization
The deserialization is just a one-liner if you happen to serialize the JSON object with the above logic.
1 | import org.json4s._ |
In fact, for any JSON string, we just also deserialize it by
1 | implicit val formats = DefaultFormats |
Summary
I find json4s to be a pleasure to work with because of its simplicity and powerful features. I think it could be a good go-to choice for Scala JSON serialization/deserialization, unless you are not using the Play Framework (Play has its own utilities to work with JSON and I am saving it for a later post).
As always, I would really appreciate your thoughts/comments. Feel free to leave them following this post or tweet me @_LeiG.