我正在尝试在我的 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/