我正在尝试像这样呈现一些响应
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呢?在使用scala模块的Play 1.0中,我成功地完成了以下操作:
def dosomeaj = {
object MyResult{
val resultCode = 0
val resultTextMessage = "sss"
}
Json(MyResult) // It's working in 1.0
}
发布于 2012-01-02 13:04:47
Play 2与Jerkson一起发布
case class Blah(blah: String)
import com.codahale.jerksHon.Json._
def act = Action { implicit request =>
Ok(generate(parse[Blah](request.body.asText.get))).as("application/json")
}
这段代码将反序列化和重新序列化json。
有关更多信息,请访问https://github.com/codahale/jerkson
发布于 2012-01-02 07:24:08
我现在已经在Play集成测试中找到了这个解决方案。
需要在app/models/MyResult2.scala中定义以下内容:
case class MyResult2(resultCode: Int, resultTextMessage: String)
object Protocol {
implicit object MyResult2Format extends Format[MyResult2] {
def writes(o: MyResult2): JsValue = JsObject(
List("resultCode" -> JsNumber(o.resultCode),
"resultTextMessage" -> JsString(o.resultTextMessage)
)
)
def reads(json: JsValue): MyResult2 = MyResult2(
(json \ "resultCode").as[Int],
(json \ "resultTextMessage").as[String]
)
}
}
在此之后,您可以像这样在您的控制器类中使用它:
import play.api._
import play.api.mvc._
import play.api.libs.json._
import models._
import models.Protocol._
object Application extends Controller {
def doAjax = Action { request =>
Ok(toJson(MyResult2(0, "Ney")))
}
}
现在需要一些手动的静态编组代码。
发布于 2014-11-10 19:55:21
您可以使用'play.api.mvc.as‘
def demo = Action {
....
Ok(jsonString).as("text/json")
}
https://stackoverflow.com/questions/8695335
复制相似问题