Search code examples
jsongrails

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.


Solution

  • 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()