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.

<!-- 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>
{
"music": {
"mobile": {
"api": {
"domain": "https://dev-music.com",
"basicAuth": {
"username": "mobile-browser",
"password": "zDPE5bBC"
}
}
}
}
}
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)
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)
}
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()
}

}

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store