vogdb
vogdb

Reputation: 4829

grails render collection as single json object

For example I have next Domain class

User{
   String name
}

Also I have 2 objects of this class

new User(name: "John").save()
new User(name: "Alex").save()

How should look "list" action in UserController to represent User.list() in JSON format like this

{1: "John", 2: "Alex"}

Let me be more precise. I want something like this:

UserController{
   def list = {
    render(contentType: "text/json") {
        User.list().each {user->
            user.id = user.name
        }
    }
}

But sadly this isn't working.

Upvotes: 4

Views: 3693

Answers (4)

Stefano Scarpanti
Stefano Scarpanti

Reputation: 313

Starting from @aldrin answer, a correction is needed for GRAILS3 json rendering because array directive is no more working (and is more correct 'application' instead of 'text'), so the solution must be

def list = {
def ulist = User.list()
render(contentType: "application/json") {
    results(ulist) { user ->
                 userid  user.id
                 username  user.name
    }
}
}

Upvotes: 0

vogdb
vogdb

Reputation: 4829

I couldn't find solution with JSONBuilder API. Because of that I made my solution with help of org.codehaus.jackson.

response.setContentType("text/json")
JsonGenerator g = jsonFactory.createJsonGenerator(response.getOutputStream())
g.writeStartObject()
for (user in users) {
    g.writeStringField(user.id.toString(), user.name)
}
g.writeEndObject()
g.close()

Upvotes: 2

aldrin
aldrin

Reputation: 4572

Try the array structure,

def list = {
    render(contentType: "text/json") {
        results = array {
            User.list().each {user->
                result "${user.id}" : "${user.name}"
            }
        }
    }
}

Upvotes: 2

Julien
Julien

Reputation: 1318

When I want to encode something as JSON in grails, I put everything in maps:

render ['1':john.name, '2':alex.name] as JSON

Upvotes: 1

Related Questions