【问题标题】:Play framework: read Json containing null values播放框架:读取包含空值的 Json
【发布时间】:2016-06-01 01:34:10
【问题描述】:

我正在尝试在我的 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 对象以接受可能的空值?

【问题讨论】:

  • 你用import play.api.libs.json._吗?
  • 是的,这就是我正在使用的导入

标签: scala playframework playframework-2.0


【解决方案1】:

您可以使用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 _)

【讨论】:

    猜你喜欢
    • 2018-01-11
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2012-07-23
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多