-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))

the second method is error custmerResultWrites, beacuse It have only one JsPath write.If i add one more part to CustomerResult ,error is ok. error:

found   : CustomersSearchResult.this.CustomerResult => Option[Seq[CustomersSearchResult.this.CustomerInfo]]
required: play.api.libs.json.Writes[Seq[CustomersSearchResult.this.CustomerInfo]]
Joan
  • 3,695
  • 1
  • 22
  • 35
haiyang
  • 190
  • 2
  • 8

1 Answers1

0

Generally, the error is due to using combinators with a single field (see answers on that question for general workarounds.)

One way to do it is:

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

which would give you an empty object ({}) if customers was empty. If instead you wanted an empty list you could do:

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

which would result in:

{
  "customers" : [ ]
}
Community
  • 1
  • 1
Mikesname
  • 8,480
  • 1
  • 41
  • 57