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写入。如果我再向客户结果添加一部分,错误是可以的。错误:

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

通常,错误是由于使用具有单个字段的组合器造成的(有关一般解决方法,请参阅有关该问题的答案。

一种方法是:

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" : [ ]
}

最新更新