我怎样才能正确地使用 Scala Play Read?

How could I properly work with Scala Play Read?

根据此文档(官方):

https://www.playframework.com/documentation/2.8.x/ScalaJsonCombinators

我必须创建一个案例 class,然后我必须创建一个 JsonReader:

val nameReads: Reads[String] = (JsPath \ "name").read[String]

然后

val nameResult: JsResult[String] = json.validate[String](nameReads)

因此,结果将进入 nameResult 并且期望可以像这样访问数据:

println(nameResult.name)

不幸的是,它不起作用。它不打印结果或 return 它们。 首先,我使用 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))

有人知道为什么编码到文档中不起作用吗?它有什么问题? 我可以使用我的代码吗?

调用 validate[User] 不是 return User,而是 JsResult[User]。这是因为 JSON 数据可能无效,您的代码需要处理这种情况。您链接到的文档中有一个示例:

json.validate[Place] match {
  case JsSuccess(place, _) => {
    val _: Place = place
    // do something with place
  }
  case e: JsError => {
    // error handling flow
  }
}