2016-02-19 53 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 _)