該庫構建於Jerkson之上,它是一個Scala包裝者,基於一個超快的基於Java的JSON庫,Jackson.html
這種方式的好處是,Java和Scala能夠共享一樣的庫(Jackson),而Scala用戶能夠享受額外類型安全的好處。val json: JsValue = Json.parse(jsonString)
val json = Json.parse(jsonString) val maybeName = (json \ "user" \ name).asOpt[String] val emails = (json \ "user" \\ "emails").map(_.as[String])
generate any Scala value to Json. For example letʼs create a simple Json object: json
只要你有一個type class 你就能將Scala類型轉成Json,很容易將任何的Scala值轉成Json.例如讓咱們建立一個簡單的Json對象: api
val jsonNumber = Json.toJson(4)
或者建立Json數組 數組
val jsonArray = Json.toJson(Seq(1, 2, 3, 4))這裏將Seq[Int]轉成Json數組沒任何問題。然而當Seq由異構的值組成時,狀況將變得複雜:
val jsonArray = Json.toJson(Seq(1, "Bob", 3, 4))沒辦法將Seq[Any]轉成Json。(Any能夠是任何非Json格式支持的對象,對吧?)
val jsonArray = Json.toJson(Seq( toJson(1), toJson("Bob"), toJson(3), toJson(4) ))
如今讓咱們看看最後一個建立更復雜的Json對象的例子:
val jsonObject = Json.toJson( Map( "users" -> Seq( toJson( Map( "name" -> toJson("Bob"), "age" -> toJson(31), "email" -> toJson("bob@gmail.com") ) ), toJson( Map( "name" -> toJson("Kiki"), "age" -> toJson(25), "email" -> JsNull ) ) ) ) )
val jsonObject = Json.toJson( Map( "users" -> Seq( toJson( Map( "name" -> toJson("Bob"), "age" -> toJson(31), "email" -> toJson("bob@gmail.com") ) ), toJson( Map( "name" -> toJson("Kiki"), "age" -> toJson(25), "email" -> JsNull ) ) ) ) )
val jsonString: String = Json.stringify(jsValue)
import com.codahale.jerkson.Json._ val json = generate( Map( "url"-> "http://nytimes.com", "attributes" -> Map( "name" -> "nytimes", "country" -> "US", "id" -> 25 ), "links" -> List( "http://link1", "http://link2" ) ) )
def sayHello = Action { request => request.body.asJson.map { json => (json \ "name").asOpt[String].map { name => Ok("Hello " + name) }.getOrElse { BadRequest("Missing parameter [name]") } }.getOrElse { BadRequest("Expecting Json data") } }
def sayHello = Action(parse.json) { request => (request.body \ "name").asOpt[String].map { name => Ok("Hello " + name) }.getOrElse { BadRequest("Missing parameter [name]") } }
curl --header "Content-type: application/json" --request POST --data '{"name": "Guillaume"}' http://localhost:9000/sayHello
HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Content-Length: 15 Hello Guillaume
def sayHello = Action(parse.json) { request => (request.body \ "name").asOpt[String].map { name => Ok(toJson( Map("status" -> "OK", "message" -> ("Hello " + name)) )) }.getOrElse { BadRequest(toJson( Map("status" -> "KO", "message" -> "Missing parameter [name]") )) } }
HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Content-Length: 43 {"status":"OK","message":"Hello Guillaume"}