Over a million developers have joined DZone.

JSON Serialization in Scala Using SBT and Play

Learn how to do JSON serialization and deserialization with the JSON Play module with some simple code samples.

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

Working with JSON is a very common task. In Scala, you can do it in many ways, either with the help of Java popular libraries such as Jackson or using Scala specific libraries. How do you choose from Spray JSON, Play JSON, Argonaut, Jackson, Rapture and others?

One day I received a test task on an interview. I had to implement a JSON serialization and deserialization of a Checkout object in the context of e-commerce.

I analyzed all existing JSON libraries for Scala (I’ve used each of them for small samples) and decided to use the Play JSON library for the task. I chose this because it has comprehensive documentation, many examples, it’s a part of the most popular Scala web framework, and I like its API.

The question was how to use the PlayFramework JSON module without the entire framework. And I’ve found a separate git repository with the Play JSON API.

For those of you who want to see how to use the Play JSON module separate of the Play Framework, keep reading.

How to Use the Play JSON Module?

Firstly, you need to add the Play JSON library to your project. You can do it in various ways – download the code of the lib and include it in the project or use some dependency management tool. Personally I use SBT in Scala projects.

That’s how we can add the Play JSON dependency to the SBT file:

name := "proectj-name"

version := "1.0"

scalaVersion := "2.11.7"

libraryDependencies ++= Seq("com.typesafe.play" % "play-json_2.11" % "2.4.2")

Then you probably want to see how JSON serialization and deserialization can be performed using this library. Let’s make a short demonstration. Here is the JSON model and we need to work with it:

  "id": 1,
  "type": "credit card",
  "address": {
    "address1": "Baker str 3",
    "address2": "",
    "city": "London",
    "zipcode": "WC064"
  "token": "u4lPaa74M"
  "cvv": 112

This is a part of the Checkout model – Payment. What do we need to do at first to implement a serialization and deserialization for this JSON model?

1. Create a Scala model for the deepest model in the JSON. Here is a case class for the Address field:

case class Address(address1: String,
                   address2: Option[String],
                   city: String,
                   state: String,
                   zipcode: String)

2. Declare writes and reads rules, which are used for writing the Scala model to JSON and for reading JSON to Scala. This logic can be declared in the Address object:

object Address {

  import play.api.libs.json._

  implicit val addressFormats = Json.format[Address]

  def writeAddress(address: Address) = {

  def readAddress(jsonAddress: JsValue) = {


As you see we use the Play’s object Json, in order to perform serialization and deserialization of an object with simple fields. By simple I mean strings, numbers, arrays and null values.

3. Perform actions #1, #2 for the parent object.

case class Payment(id: Long,
                   pType: String,
                   address: Address,
                   token: String,
                   cvv: String)

object Payment {

  import play.api.libs.json._

  def writePayment(payment: Payment) = {
      "id" -> JsNumber(payment.id),
      "type" -> JsString(payment.pType),
      "address" -> Json.toJson(payment.address),
      "token" -> JsString(payment.token),
      "cvv" -> JsString(payment.cvv)

  def readPayment(jsonPayment: JsValue) = {
    val id = (jsonPayment \ "id").as[Long]
    val pType = (jsonPayment \ "type").as[String]
    val address = (jsonPayment \ "address").as[Address]
    val token = (jsonPayment \ "token").as[String]
    val cvv = (jsonPayment \ "cvv").as[String]
    Payment(id, pType, address, token, cvv)


We get more verbose code above due to the name of the type field. Since the type word is reserved in Scala, we can not use it as a name of variables in Scala. So we have to define manually reads and writes for the Payment model.

How to Test Serialization in Scala?

In order to check that everything works fine, we can create unit tests. Add the ScalaTest dependency in the SBT file. It should look like this now:

name := "proectj-name"

version := "1.0"

scalaVersion := "2.11.7"

libraryDependencies ++= Seq(
  "org.scalatest" % "scalatest_2.11" % "3.0.0-SNAP5" % "test",
  "com.typesafe.play" % "play-json_2.11" % "2.4.2")

And write tests for the Payment:

import models._
import models.Payment._

import org.scalatest._
import play.api.libs.json._

class PaymentTest extends FlatSpec with Matchers {

  val address = Address("1375 Burlingame Ave.", None, "Burlingame", "California", "94010")

  "Payment " should "be converted to JSON correctly " in {

    val payment = Payment(1, "creditCard", address, "wdweadowei3209423", "123")
    val paymentJSON = writePayment(payment)

    (paymentJSON \ ("id")).get should be (JsNumber(1))
    (paymentJSON \ ("type")).get should be (JsString("creditCard"))
    (paymentJSON \ ("address")).get should be (Json.toJson(payment.address))
    (paymentJSON \ ("token")).get should be (JsString("wdweadowei3209423"))
    (paymentJSON \ ("cvv")).get should be (JsString("123"))


  it should " be deserialized correctly " in {
    val paymentJSON: JsValue = JsObject(Seq(
      "id" -> JsNumber(1),
      "type" -> JsString("creditCard"),
      "address" -> Json.toJson(address),
      "token" -> JsString("wdweadowei3209423"),
      "cvv" -> JsString("123")

    val payment = readPayment(paymentJSON)

    payment.id should be (1)
    payment.pType should be ("creditCard")
    payment.address should be (address)
    payment.token should be ("wdweadowei3209423")
    payment.cvv should be ("123")



The JSON Play module is really powerful. I haven’t described all of the things we can do with it, but I recommend you read the official documentation and look at more examples there. Pay attention to versions.

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

json ,scala ,play ,play framework ,sbt

Published at DZone with permission of Alexey Zvolinskiy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}