如何在 Play 框架 v2.0(来自 GIT 的最新版本)中呈现 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8695335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:07:42  来源:igfitidea点击:

How to render JSON response in Play framework v2.0 (latest build from GIT)

jsonscalaplayframework-2.0

提问by abdolence

I'm trying to render some response like this

我正在尝试像这样呈现一些响应

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!
}   

but how to map my object (MyResult) to JSON with Play 2.0? In Play 1.0 with scala module I did successfully the following:

但是如何使用 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
}    

采纳答案by andy petrella

EDIT2

编辑2

New Wiki linkfor v2.1. The old link below is not working anymore.

v2.1 的新Wiki 链接。下面的旧链接不再有效。

EDIT

编辑

We'll all be happy to read the new Wiki entry for this point. Check thisout

我们都会很高兴阅读有关这一点的新 Wiki 条目。检查



PREVIOUS

以前的

Here is the comment from the community about the state of Json support in play 2.0. link to Post

以下是社区对 play 2.0 中 Json 支持状态的评论。 链接到帖子

They are moving from Hymanson to a philosophy inspired by SJSONthat offers more control on the un/marshalling, that brings facilities to manage them, w/o the overhead of Reflection (which I agree with them is a pain for performance and is fragile against Class changes...)

他们正在从 Hymanson 转向一种受SJSON启发的哲学,它提供了对 un/marshalling 的更多控制,带来了管理它们的设施,没有反射的开销(我同意他们对性能的痛苦,并且对班级变化……)

So here is what you can read on the post:

因此,您可以在帖子中阅读以下内容:

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))
}

In the second link (SJSON), I propose you to pay special attention to the generic formatting possible by using case classand their deconstruction method (unapply).

在第二个链接 ( SJSON) 中,我建议您特别注意使用可能的通用格式case class及其解构方法 ( unapply)。

回答by Ivan Meredith

Play 2 comes with Jerkson

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")
}

This code will deserialize and reserialize the json.

此代码将反序列化和重新序列化 json。

For more information https://github.com/codahale/jerkson

欲了解更多信息https://github.com/codahale/jerkson

回答by abdolence

I've found this solution in Play integration tests right now.

我现在在 Play 集成测试中找到了这个解决方案。

It's require to define in app/models/MyResult2.scala with this content:

需要在 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]
        )
    }
}

And after this you can use it in your controller class like this:

在此之后,您可以像这样在控制器类中使用它:

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")))
    }
}

It's now required some manual static marshalling code.

现在需要一些手动静态编组代码。

回答by HasanAboShally

You can use the 'play.api.mvc.as'

您可以使用“play.api.mvc.as”

  def demo = Action {

    ....


    Ok(jsonString).as("text/json")

  }