JSON/XML Grails 2.2.3 和 2.3.11 之间的默认响应格式更改

JSON/XML default response format change between Grails 2.2.3 and 2.3.11

我们问题的根本症状是在将我们的项目从 Grails 2.2.3 切换到 2.3.11 后,我们的 jQuery Ajax 调用开始返回 XML 而不是 JSON.

下面的代码片段说明了我们的 GSP、控制器和服务中的配置方式,并显示了作为对象返回的静态数据集的示例(包含 [=68= 的字符串对的映射列表) ] 值)。控制器 returns 此列表使用 GSP 的 withFormat 子句。在 Grails 2.2.3 中,这始终是 JSON,但现在在 2.3.11 中,它是 XML。

通过实验,我发现如果我将控制器中 withFormat 子句中的 JSON 和 XML 行的顺序更改为将 JSON 放在第一位,则一切正常。我 喜欢更改每个控制器中的每个操作以使其再次工作的想法。

myTest.gsp

var fetchData = function () {
    $.ajax({
        url: "${g.createLink(controller:'myController', action:'myAction')}",
        async: true,
        type: 'get',
        dataType: "json",
        success: function (data) {
            if (data) {
                // Not shown -- Do something useful with the data
            }
        },
        error: function (request, status, error) {
            show.alert("Error with the data. \nStatus: " + status + ", \nError: " + error );
        }
    });
};

MyController.groovy

class MyController {
    def myService
    ...
    def myAction() {
        def results = myService.myAction()
        withFormat {
            xml { render results as XML }
            json { render results as JSON }
        }
    }
    ...        
}

MyService.groovy

class MyService {
    def myMap = [ AK: 'Alaska', AL:'Alabama', ... , WY:'Wyoming' ]
    def myAction() {
        def results = []
        myMap.each {
            def item = [:]
            item.code = it.key
            item.name = it.value
            result.add(item)
        }
        return results
    }
}    

Config.groovy

grails.mime.use.accept.header = true

更新:

我有一个 "fix",但我对此不是很满意,欢迎就此功能为何在 2.2.3 和 2.3.11 之间中断提供替代答案或解释。

我更改了控制器操作中 withFormat 闭包中 JSON 和 XML 类型的顺序,将 JSON 放在第一位,问题是 "resolved"。

我对此不满意,因为它需要我更改我所有控制器中的所有 68 操作。这引入了很多潜在的风险,因为其他功能可能会随着我更改此代码量而发生变化,所有这些都是为了在以前版本的 Grails 中运行良好的东西。我可以在全球范围内进行更改以解决此问题吗?

MyController.groovy

class MyController {
    def myService
    ...
    def myAction() {
        def results = myService.myAction()
        withFormat {
            json { render results as JSON } // <-- MOVED THIS TO BE FIRST
            xml { render results as XML }
        }
    }
    ...        
}

基于这篇关于接受 headers 的文章 (http://mrhaki.blogspot.com/2014/07/grails-goodness-enable-accept-header.html),我将以下行添加到我的 Config.groovy 并纠正了我的问题。

Config.groovy

grails.mime.use.accept.header = true
grails.mime.disable.accept.header.userAgents = [] // <-- Added this line