Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play JSON optional transformer

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

like image 624
Matroska Avatar asked Apr 14 '13 10:04

Matroska


1 Answers

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.

like image 125
Infinity Avatar answered Sep 23 '22 07:09

Infinity