简体   繁体   中英

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?

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),)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM