Play中JSON序列化
阿新 • • 發佈:2018-11-10
根據經驗Json處理是比較簡單的,但是Play和akka-http的序列化讓我煩惱了不少時間,所以我從自己的角度記錄一下Play的JSON處理,程式碼也都是從官方文件複製後重新整理的,下面是參考的官方文件下有幾篇JSON的文章
Working with Json
- JSON basics
- JSON with HTTP
- JSON Reads/Writes/Format Combinators
- JSON automated mapping
- JSON Transformers
實體序列化例子
1.本例中使用的實體類
package serialize case classLocation(lat: Double, long: Double) case class Resident(name: String, age: Int, role: Option[String]) case class Place(name: String, location: Location, residents: Seq[Resident])
2.序列化例子
import play.api.libs.json._ import play.api.libs.functional.syntax._ import serialize.{Location, Place, Resident} object PlayJsonTest{ def main(args:Array[String]):Unit={ implicit val locationReads = Json.reads[Location] implicit val residentReads = Json.reads[Resident] implicit val placeReads = Json.reads[Place] val json: JsValue = Json.parse(""" { "name" : "Watership Down", "location" : {"lat" : 51.235685, "long" : -1.309197 }, "residents" : [ { "name" : "Fiver", "age" : 4, "role" : null }, { "name" : "Bigwig", "age" : 6, "role" : "Owsla" } ] } """) val result: JsResult[Place] = Json.fromJson[Place](json) result match { case JsSuccess(r: Place, path: JsPath) => println("Name: " + r.name) case e: JsError => println("Errors: " + JsError.toJson(e).toString()) } } }
3.總結