DEV Community

cuongld2
cuongld2

Posted on • Updated on

Parse Json to object models in Scala using play-json

Recently, I'm working on automation performance test for the new project in our company.

The working tool I'm using is Gatling. You can check out about Gatling in here.

In the future I will write a blog series about how to use Gatling for your loadtests.

In short, Gatling is developed based on Scala, Netty and Akka.

Since I'm testing using Gatling, a lot of things will be involved working with Scala.

In this post, I will show you how to work with json in Scala.

I.About Scala

You can find out more about Scala in here

The creator of Scala is Martin Odersky. He had been using Java for quite a long time and found Java verbose,took a lot of time to write.

That's when he got the idea of creating new language.

II.How I feel about Scala

Beginning to develop in Scala seems like a tough thing. That takes me a lot of time compared to the time I learn about how to getting started in Java.

Alt Text

III.How to get started in Scala
There are some ways to get started with Scala. But for me, I find it easier to start with using IntelliJ IDEA and maven.

1.Download and install IntelliJ IDEA

Please checkout this link and download the appropriate version for you.
Then install it.

2.Download and install maven

For maven, you can checkout this link and download it.

You will need to set maven home directory so that you can use maven command everywhere in your computer.

3.Create new project in IntelliJ

You go to "File" -> "New" -> "Project" -> "Maven", choose create from Archetype, scroll down to choose "scala-archetype-simple"

IntelliJ will auto sync data for you.
You might need to set scala sdk (If yes, please follow the guide and download the Scala version - I would suggest go with 2.12.10)

After that you are ready to go.

IV.Working with JSON in Scala:
There are a lot of libraries for working with JSON. But in this tutorial, I will use play-json

1.Add dependency
Put this in your POM.xml, so that maven can download play-json to the project


<!-- https://mvnrepository.com/artifact/com.typesafe.play/play-json -->
<dependency>
    <groupId>com.typesafe.play</groupId>
    <artifactId>play-json_2.12</artifactId>
    <version>2.8.1</version>
</dependency>


2.Sample json
The sample json we are working on will be like:


{
  "music": {
    "mobile": {
      "api": {
        "domain": "https://dev-music.com",
        "basicAuth": {
          "username": "mobile-browser",
          "password": "zDPE5bBC"
        }
      }
    }
  }
}

There are nested objects in it.
music(mobile(api(domain,basicAuth(username,password))))

3.Parse json to case classes:

You might want to know what-case-class-is

First, define case class for each object in the json file:
We have Music, Mobile, Api, BasicAuth object.


case class Environments(coccocMusic: CoccocMusic)

case class CoccocMusic(mobile: Mobile)

case class Mobile(api: Api)

case class Api(domain: String, basicAuth: BasicAuth)

case class BasicAuth(username: String, password: String)

Secondly, define how to reads the json object:

object BasicAuth{
  implicit val basicAuthReads: Reads[BasicAuth] = (
    (JsPath \ "username").read[String] and
      (JsPath \ "password").read[String]
    )(BasicAuth.apply _)
}

object Api{
  implicit val apiReads: Reads[Api] = (
    (JsPath \ "domain").read[String] and
      (JsPath \ "basicAuth").read[BasicAuth]
    )(Api.apply _)
}

object Mobile{

  implicit val mobileReads: Reads[Mobile] =
    (__ \ "api").read[Api].map(Mobile.apply)
}

object CoccocMusic{

  implicit val coccocMusicReads: Reads[CoccocMusic] =
    (__ \ "mobile").read[Mobile].map(CoccocMusic.apply)
}

object Environments{
  implicit val coccocMusicReads: Reads[Environments] =
    (__ \ "music").read[CoccocMusic].map(Environments.apply)
}

4.Read the json file to text and parse it

We will define main function to run the code as below


object Main extends App {
  val filename = System.getProperty("user.dir") + "/src/main/resources/env.json"
  val bufferSource=Source.fromFile(filename)
  try {
    val source:String=bufferSource.getLines.mkString
    val jsonFormat = Json.parse(source)
    val jsonStructure = Json.fromJson[Environments](jsonFormat)
    println(jsonStructure.getOrElse(Environments).asInstanceOf[Environments].coccocMusic.mobile.api.domain)
  }
  finally {
    bufferSource.close()
  }

}

Here we have the part that assign path to variable "filename"
After that we read the file using scala.io.Source
In the try block, we read the file and parse it using play-json. Then print to console the value of api domain whether it's working

We should close the file after read using bufferSource.close()

5.Run the object Main:

You can run directly from IntelliJ by clicking the green button in Main object.

As always, you can checkout the source code from here

Peace!!!

Notes: If you feel this blog help you and want to show the appreciation, feel free to drop by :

This will help me to contributing more valued contents.

Top comments (0)