【问题标题】:How to render arbitrary JSON with the correct content type in Grails?如何在 Grails 中以正确的内容类型呈现任意 JSON?
【发布时间】:2016-03-16 22:34:21
【问题描述】:

我正在尝试输出一些简单的东西,例如 {"error": "endpoint not available"}

下面的 sn-p 以内容类型 text/html 呈现:

render ([error: 'endpoint not available']) as JSON

我也试过了:

render(contentType: 'application/json') {
  error {
    "endpoint not available"
  }
}

我知道它不会产生所需的 JSON。

如何使用 application/json 内容类型生成我想要的 JSON?

【问题讨论】:

    标签: json grails


    【解决方案1】:

    试试:

    def responseData = [
        'error': 'endpoint not available'
    ]
    render responseData as JSON
    

    【讨论】:

    • 效果很好,内容类型为 application/json。现在为什么这到底行得通而render ([error: 'endpoint not available']) as JSON 却没有?
    • @sagas This answer 可能有助于获得您想要的东西。简而言之,您必须适当地使用大括号 render ([error: 'endpoint not available'] as JSON) 应该可以工作。
    • @dmahapatro 对这个答案非常有帮助和很好的补充。
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2020-02-19
    • 2013-05-21
    • 2010-10-03
    • 1970-01-01
    相关资源
    最近更新 更多