Reputation: 9734
Given the following Reads
that validates the JSON representation of an user...
val userValidator: Reads[JsValue] = (
(__ \ 'id).readNullable[Int] ~ // how do I invoke Random.nextInt if 'id is missing?
(__ \ 'name).read[String]
).tupled ~> implicitly[Reads[JsValue]]
... how do I generate the id
key if not specified in the input JSON? Let's suppose the input JSON is something like this:
{
"name": "Joe
}
How do I add the id
key and generate its value with Random.nextInt
, so that the resulting JSON is something like this?
{
"id": 153876748,
"name": "Joe"
}
Upvotes: 1
Views: 122
Reputation: 21595
In my projects, I have defined the following method :
def withDefault[A](key: String, default: =>A)(implicit writes: Writes[A]) =
__.json.update((__ \ key).json.copyFrom((__ \ key).json.pick orElse Reads.pure(Json.toJson(default))))
Then you can write :
val _userValidator = (
(__ \ 'id).readNullable[Int] ~
(__ \ 'name).read[String]
).tupled ~> implicitly[Reads[JsValue]]
val userValidator = _userValidator.compose(withDefault("id",Random.nextInt ))
Which should do what you asked :
scala> userValidator.reads(Json.parse("""{"name": "Joe"}"""))
res6: play.api.libs.json.JsResult[play.api.libs.json.JsValue] = JsSuccess({"name":"Joe","id":721872039},)
Upvotes: 2