2016-02-19 49 views
2

我想在我的Play Scala程序中读取Json数据。该JSON可能包含在某些领域零点,所以我这是怎么定义的读取对象:播放框架:读取包含空值的Json

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对象来接受可能的空值?

+0

你用'进口play.api.libs.json._'? – vitalii

+0

是的,这是我正在使用的导入 – ps0604

回答

6

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