Build Json file in scala / play framework

I am using the Play platform with Scala and I need to specify an input that should look like this:

{ id: "node37", name: "3.7", data: {}, children:[] }, 

How can I get this format using json? Here is an example from the Play platform website:

 val JsonObject= Json.obj( "users" -> Json.arr( Json.obj( "id" -> "bob", "name" -> 31, "data" -> JsNull, "children" ->JsNull ), Json.obj( "id" -> "kiki", "name" -> 25, "data" -> JsNull, "children" ->JsNull ) ) ) 
+4
source share
2 answers
 scala> import play.api.libs.json._ import play.api.libs.json._ scala> Json.obj("id" -> "node37", "name" -> "3.7", "data" -> Json.obj(), "children" -> Json.arr()) res4: play.api.libs.json.JsObject = {"id":"node37","name":"3.7","data":{},"children":[]} 

That's what you need?

+1
source

You can also use Json library macros to convert case classes to Json

 import play.api.libs.json._ case class MyObject(id: String, name: String, data: JsObject = Json.obj(), children: Seq[MyObject]) implicit val myObjectFormat = Json.format[MyObject] 

Then, when you need the Json version of the case MyObject class, you can simply run:

 val obj = MyObject("node37", "3.7", Json.obj(), Seq()) val jsonObj = Json.toJson(obj) 

And if you have a Controller action that returns json, you can wrap it in Ok result

 Ok(jsonObj) 

And the client will see this with the corresponding Content-Type header as "application / json"

For more information on the Json library and macros, see Docs.

+1
source

Source: https://habr.com/ru/post/1480469/


All Articles