2

我正在使用 play! 的 json 组合器来验证、读取和写入 JSON。如果未设置,是否可以在读取或写入中指定默认值?

json 的验证是这样完成的(其中 json 是 JsValue):

json.validate[Pricing]

我的代码是:

case class Pricing(
    _id: ObjectId = new ObjectId,
    description: String,
    timeUnit: TimeUnit.Value,
    amount: Double = 0.0) {
        @Persist val _version = 1
}

我的读写:

implicit val pricingReads: Reads[Pricing] = (
    (__ \ "_id").read[ObjectId] and
    (__ \ "description").read[String] and
    (__ \ "timeUnit").read[TimeUnit.Value] and
    (__ \ "amount").read[Double]
)(Pricing.apply _)

implicit val pricingWrites: Writes[Pricing] = (
    (__ \ "_id").write[ObjectId] and
    (__ \ "description").write[String] and
    (__ \ "timeUnit").write[TimeUnit.Value] and
    (__ \ "amount").write[Double]
)(unlift(Pricing.unapply))

所以如果我会收到一个像这样的Json:

{"description": "some text", "timeUnit": "MONTH"}

我收到错误,该字段_id并且amount丢失了。是否可以设置默认值而不直接将其添加到 JsValue 中?

提前致谢!

4

1 回答 1

3

我宁愿使用Options:

case class Pricing(
    _id: Option[ObjectId],
    description: String,
    timeUnit: TimeUnit.Value,
    amount: Option[Double]) {
      @Persist val _version = 1
    }

并用这个替换你pricingReads的:

implicit val pricingReads: Reads[Pricing] = (
  (__ \ "_id").readNullable[ObjectId] and
  (__ \ "description").read[String] and
  (__ \ "timeUnit").read[TimeUnit.Value] and
  (__ \ "amount").readNullable[Double]
)(Pricing.apply _)

然后您的代码将适用于缺少的字段,并且您将能够做到这一点:

_id.getOrElse(new ObjectId)
于 2013-10-09T11:09:57.207 回答