6

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.

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Great. Thank you for your precise and comprehensive answer ;)
A bit too complex for me: you should instead use static responseFormats = ["json","html"] in your controller and keep the generated code as is (like respond User.list(params) ...). No need to write code to handle formats. The shame is that we should be able to use scaffold AND json without having to generate any controller code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.