play2 framework json:
case class P(
val name: String,
val age: Int,
val address: String
)
val pList = List(
P("a", 18, "USA"),
P("b", 20, "USA")
)
Json.toJson(pList)
为什么不编译?
答案 0 :(得分:3)
请查看API上的play! website和示例。它们提供了有关JSON的综合指南。由于play.api.libs.json
包仅包含七种JSON数据类型(JsObject
,JsNull
,JsUndefined
,JsBoolean
,JsNumber
,JsArray
和JsString
)你必须定义自己的格式。
取自API:
case class User(id: Long, name: String, friends: List[User])
implicit object UserFormat extends Format[User] {
def reads(json: JsValue): User = User(
(json \ "id").as[Long],
(json \ "name").as[String],
(json \ "friends").asOpt[List[User]].getOrElse(List()))
def writes(u: User): JsValue = JsObject(List(
"id" -> JsNumber(u.id),
"name" -> JsString(u.name),
"friends" -> JsArray(u.friends.map(fr => JsObject(List("id" -> JsNumber(fr.id),
"name" -> JsString(fr.name)))))))
}
//then in a controller:
object MyController extends Controller {
def displayUserAsJson(id: String) = Action {
Ok(toJson( User(id.toLong, "myName", friends: List())))
}
def saveUser(jsonString: String)= Action {
val user = play.api.libs.json.parse(jsonString).as[User]
myDataStore.save(user)
Ok
}
}
祝你好运!