【问题标题】:How could I properly work with Scala Play Read?如何正确使用 Scala Play Read?
【发布时间】: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。

标签: json scala play-json


【解决方案1】:

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

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

【讨论】:

  • 所以,我发现了错误。我的代码不起作用,因为其中一个参数为 Null,由于您的建议,我找到了它。原来你不仅要设置 type 还要设置 Null
猜你喜欢
  • 1970-01-01
  • 2015-04-15
  • 2015-10-19
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
  • 2017-09-14
相关资源
最近更新 更多