-5

play2 框架 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)

为什么这不编译?

4

1 回答 1

3

请看API和play上的例子!网站。它们提供了有关 JSON 的综合指南。由于该play.api.libs.json包仅包含七种 JSON 数据类型(JsObjectJsNullJsUndefinedJsBoolean、和) JsNumber,因此您必须定义自己的格式。JsArrayJsString

取自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
   }
}

祝你好运!

于 2012-10-31T09:07:42.467 回答