我有以下案例类:
case class User(name: String, age: String)
我正在尝试为它实现JSON Reads
转换器,因此我可以执行以下操作:
val user = userJson.validate[User]
...但传入的JSON结构略有不同:
{ "age": "12", "details": { "name": "Bob" } }
如何实现我的JSON Reads
转换器?
答案 0 :(得分:1)
您可以使用组合器来解析子路径。
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),)