如何在Grails中呈现JSON?

如何在Grails中呈现JSON?,grails,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 ]} 它对格式错误的数据进行渲染,

我的目标是

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


请参阅《grails用户指南》的一节使用
collect
而不是
each
,如

def res = roles.collect {['value':it.id, 'text':it.name]}
render res as JSON
对于Grails3,它呈现{“数组”:{“角色”:{“文本”:“…”,“值”:“…}}
def res = roles.collect {['value':it.id, 'text':it.name]}
render res as JSON