Scala

Scala: working with JSON

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

One day I received a test task on an interview. According to it, I had to implement a JSON serialisation and deserialisation of a Checkout object in context of e-commerce. I analysed all existing JSON libraries for Scala, I’ve used each of them for small samples and decided to take the Play JSON library for the task. I did it because it has a 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 PlayFramework JSON module without the entire framework. And I’ve found a separate git repository with exactly Play JSON API.

For those of you who want to see how to use the Play JSON module separately of the Play Framework, I continue the post.

How to use Play JSON module?

Firstly you need to add the Play JSON library to your project. You can do it in various ways – download a 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 serialisation and deserialisation can be performed using this library. Well, 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 serialisation and deserialisation 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 of Scala model to JSON and for reading of 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) = {
        Json.toJson(address)
      }
    
      def readAddress(jsonAddress: JsValue) = {
        jsonAddress.as[Address]
      }
    
    }

    As you see we use the Play’s object Json, in order to perform serialisation and deserialisation of 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) = {
        JsObject(Seq(
          "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, its 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 serialisation & serialisation 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")
  }

}

Summary

JSON Play module is really powerful. I haven’t describe a lot of things which can be done with its help. But I recommend you to read the official documentation and look at more examples there. Pay extra attention to versions of docs which you read and Scala which you use in a project.

Reference: Scala: working with JSON from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog.

Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button