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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Coding
  3. Languages
  4. JSON Serialization in Scala Using SBT and Play

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.

Alexey Zvolinskiy user avatar by
Alexey Zvolinskiy
·
Nov. 08, 15 · Tutorial
Like (8)
Save
Tweet
Share
15.21K Views

Join the DZone community and get the full member experience.

Join For Free

scala-logo
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) = {
    json.tojson(address)
  }

  def readaddress(jsonaddress: jsvalue) = {
    jsonaddress.as[address]
  }

}

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) = {
    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 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")
  }

}

summary

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.

Scala (programming language) Serialization JSON

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How Do the Docker Client and Docker Servers Work?
  • 9 Ways You Can Improve Security Posture
  • What Is Testing as a Service?
  • What Was the Question Again, ChatGPT?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: