scala web

Play Framework

Json parsing

play-json allows to create complex tree by nesting case classes.

import play.api.libs.json.Reads._
import play.api.libs.json._
import play.api.libs.functional.syntax._


case class Overall(overall: Double)
case class Data(association_score: Overall)
case class RootJson(from: Int, total: Int, data: Seq[Data])

// this for simple element case class
implicit val overallReads: Reads[Overall] =
  (JsPath \ "overall").read[Double].map(Overall)

implicit val dataReads: Reads[Data] =
  (JsPath \ "association_score").read[Overall].map(Data)

// this for multiple element case class
implicit val rootJsonReads: Reads[RootJson] = (
  (JsPath \ "from").read[Int] and
    (JsPath \ "total").read[Int] and
    (JsPath \ "data").read[Seq[Data]]
)(RootJson.apply _)

then this json can be parsed:

    val json: String = """
  {
    "total" : 1000,
    "from" : 10,
    "data" : [ {
      "association_score" : {
           "overall" : 40.0
      }
    } ]
  }
  """
  
Json.parse(json).validate[RootJson] match {
  case JsSuccess(rootJson, _) => {
    val _: RootJson = rootJson
    rootJson
  }
  case e: JsError => {
    // error handling flow
    throw new Exception
  }
}

React ?

This page was last modified: