有許多方法可以通過Play JSON庫來實現。主要區別在於Scala案例類的使用與否。
給出一個簡單的JSON
val json = Json.parse("""{"people": [ {"name":"Jack", "age": 19}, {"name": "Tony", "age": 26} ] }""")
您可以使用案例類和JSON宏來自動分析數據
import play.api.libs.json._
case class People(name: String, age: Int)
implicit val peopleReader = Json.reads[People]
val peoples = (json \ "people").as[List[People]]
peoples.foreach(println)
或者不區分階級,手動
import play.api.libs.json._
import play.api.libs.functional.syntax._
implicit val personReader: Reads[(String, Int)] = (
(__ \ "name").read[String] and
(__ \ "age").read[Int]
).tupled
val peoples = (json \ "people").as[List[(String, Int)]]
peoples.foreach(println)
在其他單詞,請查看關於此主題的非常完整的文檔:) http://www.playframework.com/documentation/2.1.0/ScalaJson
注意:我也願意爲JSON使用完全不同的庫,而不是與Play集成的庫。但是,我不想。 – Commander 2013-03-26 18:15:37