2013-10-09 54 views
2

我使用play!的json組合器來驗證,讀取和寫入JSON。如果它們沒有設置,是否可以在讀取或寫入中指定默認值? JSON的使用Play設置默認值! Json Combinators

驗證這樣的(其中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"} 

我收到錯誤,該字段缺少_idamount。有沒有可能在不將它直接添加到JsValue的情況下設置默認值?

在此先感謝!

回答

3

我寧願使用Option S:

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

這是使用'Option'的好處。但不幸的是它不能使用ObjectId(我使用play-salat作爲ORM)。無論如何,它適用於其他領域... – 3x14159265