Created
July 20, 2012 11:12
-
-
Save krdlab/3150209 to your computer and use it in GitHub Desktop.
Json データの変換 (on Play framework 2.0.2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
↓こんな JSON データの変換 (Play framework 2.0.2) | |
{ | |
"users": [ | |
{ "name" : "krdlab", "point": 12345 }, | |
{ "name" : "hoge", "point": 2000 }, | |
... | |
] | |
} | |
*/ | |
// ↓こんな感じで用意して | |
import play.api.libs.json.{ JsValue, JsString, JsNumber, JsObject, Format } | |
case class User(name: String, point: Int) | |
object User { | |
implicit object UserFormat extends Format[User] { | |
def reads(json: JsValue): User = User( | |
(json \ "name").as[String], | |
(json \ "point").as[Int]) | |
def writes(user: User): JsValue = JsObject(Seq( | |
"name" -> JsString(user.name), | |
"point" -> JsNumber(user.point))) | |
} | |
} | |
// ↓こんな感じで呼び出す | |
// ---- | |
// scala> val json = Json.parse("{\"users\":[{\"name\":\"krdlab\",\"point\":12345},{\"name\":\"hoge\",\"point\":2000}]}") | |
// json: play.api.libs.json.JsValue = {"users":[{"name":"krdlab","point":12345},{"name":"hoge","point":2000}]} | |
// | |
// scala> (json \ "users").as[Array[JsObject]].map(_.as[User]).toList | |
// res0: List[User] = List(User(krdlab,12345), User(hoge,2000)) | |
// ---- | |
// [参考] | |
// Format: | |
// http://stackoverflow.com/questions/10488950/play2-does-not-find-my-implicit-reads-or-format-for-json | |
// Array の読み込み: | |
// https://groups.google.com/forum/?fromgroups#!topic/play-framework/BsG1tnpYgm4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment