jsonscalaplayframeworkplayframework-json

Play Scala JSON Reads converter: mapping nested properties


I have the following case class:

case class User(name: String, age: String)

I am trying to implement a JSON Reads converter for it, so I can do the following:

val user = userJson.validate[User]

… but the incoming JSON has slightly different structure:

{ "age": "12", "details": { "name": "Bob" } }

How can I implement my JSON Reads converter?


Solution

  • You can do this using combinators to parse sub-paths.

    import play.api.libs.json._
    import play.api.libs.functional.syntax._
    
    case class User(name: String, age: String)
    
    val js = Json.parse("""
        { "age": "12", "details": { "name": "Bob" } }
    """)
    
    implicit val reads: Reads[User] = (
        (__ \ "details" \ "name").read[String] and
        (__ \ "age").read[String]
    )(User.apply _)    
    
    scala> js.validate[User]
    res2: play.api.libs.json.JsResult[User] = JsSuccess(User(Bob,12),)