【问题标题】:grails 3.3 render JSON broken?grails 3.3 渲染 JSON 损坏?
【发布时间】:2017-07-15 17:16:57
【问题描述】:

我们正在尝试让 grails 2.5 项目在 grails 3.3 中运行

我们有一个 json API,即用 JSON 响应的控制器:

            log.info("about to return json")
            render(status: 200, contentType: 'application/json') {
                [
                    'result': 9999,
                    'message': "hello"
                ]
            }

问题是输出总是“{}”。这是控制器方法的最后一段代码。

如果我们这样做:

 render("hello")

我们得到“你好”。

如果我们这样做:

    render(status: 200, contentType: 'application/json') {
                    result = 0
                    player = "hello"
            }

我们也总是得到“{{}”,这看起来很疯狂!

有什么想法吗?这在grails 3.3中被破坏了吗?相同的代码在 grails 2.5 中完美运行

目前,我们能找到的唯一解决方案是使用字符串连接手动渲染 JSON,这既繁琐又容易出错。

【问题讨论】:

    标签: json grails


    【解决方案1】:

    深入研究源代码,似乎 grails 3 已将负责 JSON 渲染的类更改为 StreamingJsonBuilder。它的语法略有不同,破坏了现有的 2.5 代码。遗憾的是,渲染文档和示例仍然具有“旧”格式。

    有两种选择:

    1 使用新格式,例如:

    render(status: 200, contentType: 'application/json') {
           result 0
           player "hello"
    }
    

    这样做的缺点是它不适用于自定义对象编组器。

    2 使用 JSONBuilder,例如

    def builder = new JSONBuilder()
    def json = builder.build {
            result= "0"
            player= "hello"
     }
     render(status: 200, contentType: 'application/json', text: json)
    

    这有两个优点:它适用于 Grails 2.5 和 3.x,因此可以适用于 grails 4.x。此外,它还可以与 Object Marshallers 一起使用,从而节省大量代码。

    自定义对象编组器如下所示:

        DecimalFormat df = new DecimalFormat("##0.00");
        JSON.registerObjectMarshaller(Account) {
            return [balance: df.format(it.balance), currencyIso: it.currencyIso, id: it.id]
        }
    

    然后你把它们放在你的 bootstrap.groovy 中(从 conf 移到 init 并在 3.x 中给出了不同的包)

    【讨论】:

    猜你喜欢
    • 2017-06-05
    • 1970-01-01
    • 2011-05-17
    • 2012-03-27
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多