Reputation: 3132
I am using the Play framework with Scala, and I need to give an input which has to look like so: :
{
id: "node37",
name: "3.7",
data: {},
children:[]
},
How can I obtain that format with json? Here is the example from the Play framework's 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
)
)
)
Upvotes: 4
Views: 918
Reputation: 762
You may also want to use the Json libraries macros for converting 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 in when you want a Json version of the MyObject
case class you can just 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 an Ok result
Ok(jsonObj)
And the client will see this with the proper Content-Type header as "application/json"
You can find more information about the Json Library and the Macros in the Docs
Upvotes: 1
Reputation: 11830
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":[]}
This is what you need?
Upvotes: 1