views:

41

answers:

1

Ok, I have a very simple app created in Grails. I have a generated domain class (Person) and its generated controller, using the automatic Grails scaffold:

package contacts

class PersonController {

    def scaffold = Person

}

Now I'd like to get a JSON representation of a Person object.

Do I have to change the view or the controller? And how?

Thank you.

+5  A: 

Add the following to your controller:

def list = {
    params.max = Math.min(params.max ? params.int('max') : 10, 100)
    def personList = Person.list(params)
    withFormat {
        html {
            [personInstanceList: personList, personInstanceTotal: Person.count()]
        }
        json {
            render personList as JSON
        }
    }
}

This should support both your scaffolding and the JSON output.

You can access the scaffolding as:

http://localhost:8080/contacts/person/list

You can access the Person list as json with:

http://localhost:8080/contacts/person/list?format=json

There are other ways to do it too, but I like doing it this way to leave the scaffolding around for testing.

Lloyd Meinholz
Great. Thank you for your precise and comprehensive answer ;)
daliz