playframework json 写问题

playframework json write quesstion

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 write.If我在CustomerResult中添加了一个部分,错误是可以的。 错误:

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

一般来说,该错误是由于使用 combinators with a single field(请参阅该问题的一般解决方法的答案。)

一种方法是:

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

如果 customers 是空的,这会给你一个空对象 ({})。相反,如果你想要一个空列表,你可以这样做:

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

这将导致:

{
  "customers" : [ ]
}