我正在使用 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 中?
提前致谢!