Hikaru Shindo
Hikaru Shindo

Reputation: 2913

How to render JSON in Grails?

I have an object as,

def roles = account.roles

I want to render it in JSON format like

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

When I did the code like this, it's not working,

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

It render to the data that has wrong format like {"value":[1,2,3],"text":["Admin","Owner","Sale"]}

And I try like this

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

It's not working either.

Upvotes: 3

Views: 3948

Answers (2)

MKB
MKB

Reputation: 7619

Use collect instead of each, like

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

Upvotes: 4

Sudhir N
Sudhir N

Reputation: 4096

You can either do, render roles as JSON

Or

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

See xml and json responses section of grails user guide

Upvotes: -1

Related Questions