播放框架:读取 Json 包含空值
Play framework: read Json containing null values
我正在尝试读取我的 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 案例 class:
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 _)
我正在尝试读取我的 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 案例 class:
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 _)