如何在 Grails 中渲染 JSON?

How to render JSON in Grails?

我有一个对象,

def roles = account.roles

我想以 JSON 格式呈现它,例如

[{'value':1, 'text':'Admin'},{'value':2,'text':'Owner'}, {'value':3,'text':'Sale'}]

当我编写这样的代码时,它不起作用,

render(contentType: "text/json"){[
    "value" : roles.id,
    "text" : roles.name
]}

它呈现格式错误的数据,如 {"value":[1,2,3],"text":["Admin","Owner","Sale"]}

然后我这样尝试

def res = roles.each(){
    ['value':it.id, 'text':it.name]
}
render res as JSON

也不行。

您可以将角色渲染为 JSON

render(contentType: "application/json") {
        roles = array {
            for (r in roles) {
                role text: r.name, value:r.id
            }
        }
    }

请参阅 grails 用户指南的 xml and json responses 部分

使用collect代替each,比如

def res = roles.collect {['value':it.id, 'text':it.name]}
render res as JSON