4

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
    )
  )
)

2 Answers 2

1
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?

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.