手動建立 JSON
你可以手動構建 JSON 物件樹(JsValue
)
import play.api.libs.json._
val json = JsObject(Map(
"name" -> JsString("Jsony McJsonface"),
"age" -> JsNumber(18),
"hobbies" -> JsArray(Seq(
JsString("Fishing"),
JsString("Hunting"),
JsString("Camping")
))
))
或者使用較短的等效語法,基於一些隱式轉換:
import play.api.libs.json._
val json = Json.obj(
"name" -> "Jsony McJsonface",
"age" -> 18,
"hobbies" -> Seq(
"Fishing",
"Hunting",
"Camping"
)
)
要獲取 JSON 字串:
json.toString
// {"name":"Jsony McJsonface","age":18,"hobbies":["Fishing","Hunting","Camping"]}
Json.prettyPrint(json)
// {
// "name" : "Jsony McJsonface",
// "age" : 18,
// "hobbies" : [ "Fishing", "Hunting", "Camping" ]
// }