Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON output of a view in Grails

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.

like image 766
daliz Avatar asked May 03 '10 12:05

daliz


1 Answers

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.

like image 118
Lloyd Meinholz Avatar answered Nov 15 '22 09:11

Lloyd Meinholz