2013-10-09 3 views
2

나는 play!의 json 연결자를 사용하여 JSON의 유효성을 검사하고 읽고 쓰며 사용하고 있습니다. 설정되지 않은 경우 읽기 또는 쓰기의 기본값을 지정할 수 있습니까? JSON의기본값을 설정하십시오. 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에 직접 추가하지 않고 기본값을 설정할 수 있습니까?

미리 감사드립니다.

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

및 교체하여 pricingReads를이와 함께 :

답변

3

차라리 Option의를 사용하십시오

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

이는 '옵션'을 사용하는 것이 좋습니다. 하지만 불행히도'ObjectId' (나는 ORM으로 play-salat을 사용하고 있습니다)와 함께 작동하지 않습니다. 어쨌든 그것은 다른 분야에서 작동합니다 ... – 3x14159265

관련 문제