Play Scala JSON 读取转换器:映射嵌套属性

Play Scala JSON Reads converter: mapping nested properties

我有以下情况class:

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

我正在尝试为其实现一个 JSON Reads 转换器,因此我可以执行以下操作:

val user = userJson.validate[User]

... 但传入的 JSON 结构略有不同:

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

如何实现我的 JSON Reads 转换器?

您可以使用组合器来解析子路径。

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