2016-03-07 45 views
-2
case class CustomerInfo (
    customerId: Long, 
    customerName: String, 
    cameAt: String, 
    staffId:String, 
    staffName:String 
) 

case class CustomerResult (
    customers:Option[Seq[CustomerInfo]] = None 
){ 
    def toJson = Json.toJson(this) 
} 

implicit val customerInfoWrites: Writes[CustomerInfo] = (
     (JsPath \ "customer_id").write[Long] and 
     (JsPath \ "customer_name").write[String] and 
     (JsPath \ "came_at").write[String] and 
     (JsPath \ "staff_id").write[String] and 
     (JsPath \ "staff_name").write[String] 
)(unlift(CustomerInfo.unapply)) 

implicit val custmerResultWrites: Writes[CustomerResult] = (
     (JsPath \ "customers").writeNullable[Seq[CustomerInfo]] 
)(unlift(CustomerResult.unapply)) 

第二種方法是錯誤custmerResultWrites,因爲它只有一個JsPath寫入。如果我再向CustomerResult添加一個部分,錯誤是可以的。 錯誤:playframework json write quesstion

found : CustomersSearchResult.this.CustomerResult => Option[Seq[CustomersSearchResult.this.CustomerInfo]] 
required: play.api.libs.json.Writes[Seq[CustomersSearchResult.this.CustomerInfo]] 

回答

0

一般情況下,誤差是由於使用combinators with a single field

一種方式做到這一點的(見答案對一般的解決方法這個問題。):

​​

這將如果customers爲空,給你一個空對象({})。相反,如果你想要一個空的列表,你可以這樣做:

val custmerResultWrites2: Writes[CustomerResult] = 
    (JsPath \ "customers").writeNullable[Seq[CustomerInfo]].contramap { 
    case CustomerResult(None) => Some(Seq.empty[CustomerInfo]) 
    case CustomerResult(seq) => seq 
    } 

這將導致:

{ 
    "customers" : [ ] 
} 
+0

哦,三江源這麼多,我有我的resovle問題 – haiyang