【问题标题】:playframework json write quesstion玩框架json写题
【发布时间】:2016-03-07 11:37:07
【问题描述】:
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 中再添加一个部分,则错误是可以的。 错误:

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

【问题讨论】:

    标签: scala playframework playframework-2.0


    【解决方案1】:

    一般来说,错误是由于使用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" : [ ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多