我正在尝试做出这样的回应
def doAjax = Action { request =>
object MyResult {
val resultCode = 0
val resultTextMessage = "sss"
}
Ok(Json(MyResult)) // It's not working anymore - not compiling in v2.0!
}
但如何使用 Play 2.0 将我的对象 (MyResult) 映射到 JSON?
在 Play 1.0 with scala 模块中,我成功执行了以下操作:
def dosomeaj = {
object MyResult{
val resultCode = 0
val resultTextMessage = "sss"
}
Json(MyResult) // It's working in 1.0
}
EDIT2
New 维基链接 http://www.playframework.com/documentation/2.1.x/ScalaJsonRequests对于 v2.1。下面的旧链接不再有效。
EDIT
我们都很乐意阅读关于这一点的新 Wiki 条目。查看this https://github.com/playframework/Play20/wiki/Scalajson out
PREVIOUS
以下是社区对 play 2.0 中 Json 支持状态的评论。链接到帖子 https://groups.google.com/d/msg/play-framework/VeVacV4CU1o/Zm5gzwF7PScJ
他们正在从杰克逊转向受启发的哲学SJSON http://debasishg.blogspot.com/2010/07/sjson-now-offers-type-class-based-json.html它提供了对取消/编组的更多控制,带来了管理它们的设施,没有反射的开销(我同意他们的观点,这对性能来说是一种痛苦,并且对于类更改来说很脆弱......)
因此,您可以在帖子中读到以下内容:
case class Blah(blah: String)
// if you want to directly serialize/deserialize, you need to write yourself a formatter right now
implicit object BlahFormat extends Format[Blah] {
def reads(json: JsValue): Blah = Blah((json \ "blah").as[String])
def writes(p: Blah): JsValue = JsObject(List("blah" -> JsString(p.blah)))
}
def act = Action { implicit request =>
// to get a Blah object from request content
val blah = Json.parse(request.body.asText.get).as[Blah]
// to return Blah as application/json, you just have to convert your Blah to a JsValue and give it to Ok()
Ok(toJson(blah))
}
在第二个链接中(SJSON http://debasishg.blogspot.com/2010/07/sjson-now-offers-type-class-based-json.html),我建议您特别注意使用可能的通用格式case class
及其解构方法(unapply
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)