Construct a Json File in scala / play framework

2019-06-24 03:04发布

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条回答
Lonely孤独者°
2楼-- · 2019-06-24 03:34

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

查看更多
神经病院院长
3楼-- · 2019-06-24 03:42
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?

查看更多
登录 后发表回答