scala - Play Framework : read Json containing null values

标签 scala playframework playframework-2.0

我正在尝试在我的 Play Scala 程序中读取 Json 数据。 Json 可能在某些字段中包含空值,所以这就是我定义 Reads 对象的方式:

  implicit val readObj: Reads[ApplyRequest] = (
      (JsPath \ "a").read[String] and
      (JsPath \ "b").read[Option[String]] and
      (JsPath \ "c").read[Option[String]] and
      (JsPath \ "d").read[Option[Int]]
    )  (ApplyRequest.apply _) 

和 ApplyRequest 案例类:
case class ApplyRequest ( a: String,
                          b: Option[String],
                          c: Option[String],
                          d: Option[Int],
                          )

这不编译,我得到 No Json deserializer found for type Option[String]. Try to implement an implicit Reads or Format for this type.
如何声明 Reads 对象以接受可能的空值?

最佳答案

您可以使用 readNullable 解析丢失或 null领域:

implicit val readObj: Reads[ApplyRequest] = (
  (JsPath \ "a").read[String] and
  (JsPath \ "b").readNullable[String] and
  (JsPath \ "c").readNullable[String] and
  (JsPath \ "d").readNullable[Int]
)  (ApplyRequest.apply _)

关于scala - Play Framework : read Json containing null values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35505969/

相关文章:

java - 如何将多个不同的 InputStream 链接到一个 InputStream

scala - 如何在返回类型中保留多态函数的参数类型

scala - Play/Scala 将 Controller 注入(inject)测试

java - 将 json 对象传递给 play-framework 操作

java - 如何为 Play Framework 项目编写 Maven POM 文件?

scala - 无法让 sbt-concat 捆绑来自 sbt-sass 或 sbt-less 的样式

jquery - Play 框架和 javascript i18n

scala - 我应该使用 executeUpdate 还是 execute 删除带有 Anorm 的行?

scala - 与列表一样, map 为 Nil

scala - 如何在 Play2.1 框架中利用 SLF4J varargs 日志记录?