【问题标题】:Change Content-Type of JSON response while using 'as JSON' to render response在使用“as JSON”呈现响应时更改 JSON 响应的 Content-Type
【发布时间】:2011-11-01 07:51:46
【问题描述】:

似乎在 Grails 中,默认 contentType 用于在使用如下内容时呈现 JSON 响应:

render Book.list(params) as JSON

是应用程序/json

当然还有一种更简单的方法来定义内容类型:

render(contentType:"text/json") {
    book(title:b.title,author:b.author)
}

有没有办法使用速记方式,并且仍然得到“text/json”的响应内容类型?

注意:示例取自here

【问题讨论】:

    标签: json grails content-type


    【解决方案1】:

    在您的 grails config.groovy 中,您可以设置以下 mime 类型属性。

    grails.mime.types = [ html: ['text/html','application/xhtml+xml'],
                    xml: ['text/xml', 'application/xml'],
                    text: 'text/plain',
                    js: 'text/javascript',
                    rss: 'application/rss+xml',
                    atom: 'application/atom+xml',
                    css: 'text/css',
                    csv: 'text/csv',
                    all: '*/*',
                    json: ['application/json','text/json'],
                    form: 'application/x-www-form-urlencoded',
                    multipartForm: 'multipart/form-data'
    ]
    

    尝试将 json 属性的值列表的顺序更改为 ['text/json','application/json']

    【讨论】:

    • 它不像我们所拥有的那样工作: /** * 将 JSON Writer 定向到 HttpServletResponse 的输出流并将 Content-Type 设置为 application/json * * @param response a HttpServletResponse * @ throws ConverterException */ public void render(HttpServletResponse response) throws ConverterException { response.setContentType(GrailsWebUtil.getContentType("application/json", encoding));尝试{渲染(response.getWriter()); } catch (IOException e) { throw new ConverterException(e); } } 在 JSON.java 中
    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多