I am using Play 2.1 JSON Reads to achieve a conditional transformation.
I have a json object and I want to transform an optional field removing \n chars.The problem is that if I remove the content from the sent JSON, I obtain a validation error.
This field is optional and I don't know how to describe that the transformation is optional. This is the current content transformation:
val transformContent = (__ \ 'content).json.update(__.read[JsString].map{
value =>
JsString(value.value.replaceAll("\n", ""))
})
How can I obtain an optional field transformation? Should I use the Reads.verifyingIf
?
Thanks
You can do this:
val json = Json.obj("whatever" -> 1, "content" -> "hello world")
val json2 = Json.obj("whatever" -> 1)
val transformer = (__ \ 'content).json.update(
__.readOpt[JsString].map{
case Some(JsString(str)) => JsString(str.replaceAll("world", "scala"))
}
).orElse(__.json.pick[JsObject])
json.transform(transformer)
//JsSuccess({"whatever":1,"content":"hello scala"},)
json2.transform(transformer)
//JsSuccess({"whatever":1},)
Little hacky, but it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With