Play2 add new field to JsObject
Asked Answered
S

1

5

Is it possible to add new field to JsObject?

val jsonObj = Json.obj()
jsonObj.put("field" -> 100) <==== Somthing like this

I have a lot of methods that add new fields. How can I dynamically create JsObject?

Save answered 27/2, 2014 at 18:23 Comment(2)
I found something like this: jsonObj ++= Json.obj("field" -> 100) Do I always have to create new JsObject?Grevera
Yes you do. play.api.libs.json... objects are immutableMathison
A
11

Yes, you can add a new field using the "+" method. Note that the object is immutable, so this will create a new copy of the JsObject with the added field:

val obj = Json.obj()
// obj - {}
val newObj = obj + ("name" -> JsString("Kip"))
// newObj - {"name":"Kip"}
Auberta answered 27/2, 2014 at 18:57 Comment(1)
You might be tempted to try, after looking at the source of JsObject + val newObj = obj + ("name", JsString("Kip")) But if you run -Xlint in the compiler option, you will get this warning: Adapting argument list by creating a 2-tuple: this may not be what you want.Bladdernose

© 2022 - 2024 — McMap. All rights reserved.