Play Framework - add a field to JSON object Play Framework - add a field to JSON object json json

Play Framework - add a field to JSON object


JsObject has a + method that allows you to add fields to an object, but unfortunately your jsonObject is statically typed as a JsValue, not a JsObject. You can get around this in a couple of ways. The first is to use as:

 scala> jsonObject.as[JsObject] + ("c" -> Json.toJson(3)) res0: play.api.libs.json.JsObject = {"a":1,"b":2,"c":3}

With as you're essentially downcasting—you're telling the compiler, "you only know that this is a JsValue, but believe me, it's also a JsObject". This is safe in this case, but it's not a good idea. A more principled approach is to use the OWrites directly:

scala> val jsonObject = classAWrites.writes(classAObject)jsonObject: play.api.libs.json.JsObject = {"a":1,"b":2}scala> jsonObject + ("c" -> Json.toJson(3))res1: play.api.libs.json.JsObject = {"a":1,"b":2,"c":3}

Maybe someday the Json object will have a toJsonObject method that will require a OWrites instance and this overly explicit approach won't be necessary.


I found a solution myself. In fact the JsValue, which is the return type of Json.toJson has no such method, but the JsObject (http://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.libs.json.JsObject) does, so the solution is:

val jsonObject = Json.toJson(classAObject).as[JsObject]jsonObject + ("c", JsNumber(3)) 

I hope someone will find this useful :)


simpler way is to use argoanut (http://argonaut.io/)

var jField : Json.JsonField = "myfield" //Json.JsonField is of type Stringobj1.asJson.->:(jField, obj2.asJson)  // adds a field to obj1.asJson

here obj1.asJson creates a JSON objectand obj2 is the object to be added to the json created by obj1.asJson