Grails 2 - 自动生成JSON输出(就像Spring 3.x一样)

nic*_*dos 7 grails json

在Spring MVC 3.x中,我可以ContentNegotiatingViewResolver通过将文件扩展名更改为.json或者,将bean 配置为自动呈现JSON或XML中的任何给定端点.xml.我假设Grails中有相同的功能但我找不到它.

我读过的所有内容都说我必须捕获传入的mime类型(使用withFormat),然后render as JSON在我的每个控制器方法中使用(或等效)指定JSON输出(例如,使用Grails渲染JSON?).在我深入研究并开始向控制器添加JSON特定代码之前,我想我会问这里......

所以我的问题是:我是否可以通过简单地为任何给定的URL添加".json"文件扩展名(或更改接受标头)来配置Grails 2来自动生成JSON输出?

Fab*_*oli 7

我认为你可以使用grails过滤器轻松地使用它

这是我在矿山应用程序中使用OA OS API执行的过滤器,它基于接受头执行xml,json和yalm

class RenderFilters {

    def grailsApplication

    def filters = {

        multiFormat(controller: '*EndPoint', action: '*', search: true) {

            after = { Map model ->

                def accepts = request.getHeaders('accept')*.toLowerCase()

                def out = model.containsKey('out')?model.out:model

                if(accepts.any{ it.contains('json')  }){
                    render(text: out as JSON, contentType: 'application/json', encoding:"UTF-8")
                }

                else if(accepts.any{ it.contains('yaml')  }){
                    render(text: Yaml.dump(out), contentType: 'application/x-yaml;', encoding:"UTF-8")
                }

                else if(accepts.any{ it.contains('html')  }){
                    render(text: out as JSON, contentType: 'application/json', encoding:"UTF-8")
                }

                else if(accepts.any{ it.contains('xml')  }){
                    render(text: out as XML, contentType: 'application/xml', encoding:"UTF-8")
                }

                else {
                    render(text: out as JSON, contentType: 'application/json', encoding:"UTF-8")
                }
                false
            }

            before = {

                def contentType = request.getHeader('Content-Type')?.toLowerCase()

                if(!contentType) return true

                if(contentType == 'application/json'){
                    params.body = JSON.parse(request.reader)                    
                    }
                if(contentType == 'application/xml'){
                    params.body = XML.parse(request.reader)
                    }
                if(contentType == 'application/x-yaml'){
                    params.body = Yaml.load(request.reader)
                    }

                params.body = new TypeConvertingMap((Map) params.body)              

                true
                }

        }

    }
}
Run Code Online (Sandbox Code Playgroud)