【发布时间】:2020-11-28 16:10:28
【问题描述】:
根据本文档(官方):
https://www.playframework.com/documentation/2.8.x/ScalaJsonCombinators
我必须创建一个案例类,然后我必须创建一个 JsonReader:
val nameReads: Reads[String] = (JsPath \ "name").read[String]
然后
val nameResult: JsResult[String] = json.validate[String](nameReads)
因此,结果将进入 nameResult 并且期望数据可以像这样访问:
println(nameResult.name)
不幸的是,它不起作用。它不打印结果或返回它们。
首先,我使用 Future 并从网络读取 JSON
implicit val context = scala.concurrent.ExecutionContext.Implicits.global
val userReads: Reads[User] = (
(JsPath \ "id").read[Int] and
(JsPath \ "login").read[String]
)
val futureResult = wc.url(path).get().map {
response =>
response.json.validate[User](userReads)
}
futureResult.map(r => println(r.id, r.login))
但是!此代码有效,但不在文档中。
implicit val context = scala.concurrent.ExecutionContext.Implicits.global
val userReads: Reads[User] = (
(JsPath \ "id").read[Int] and
(JsPath \ "login").read[String]
)
val futureResult = wc.url(path).get().map {
response =>
UserTest(
(response.json \ "id").as[String],
(response.json \ "login").as[String]
)
}
futureResult.map(r => println(r.id, r.login))
有人知道为什么文档中的代码不起作用吗?它有什么问题? 我可以使用我的代码吗?
【问题讨论】:
-
其中一个参数为 Null,但设置为 String。