10.10.5 JSON Views by Convention

There are a few useful conventions you can follow when creating JSON views. For example if you have a domain class called Book, then creating a template located at grails-app/views/book/_book.gson and using the respond method will result in rendering the template:

  1. def show(Long id) {
  2. respond Book.get(id)
  3. }

In addition if an error occurs during validation by default Grails will try to render a template called grails-app/views/book/_errors.gson, otherwise it will try to render grails-app/views/errors/_errors.gson if the former doesn’t exist.

This is useful because when persisting objects you can respond with validation errors to render these aforementioned templates:

  1. @Transactional
  2. def save(Book book) {
  3. if (book.hasErrors()) {
  4. transactionStatus.setRollbackOnly()
  5. respond book.errors
  6. }
  7. else {
  8. // valid object
  9. }
  10. }

If a validation error occurs in the above example the grails-app/views/book/_errors.gson template will be rendered.

For more information on JSON views (and Markup views), see the JSON Views user guide.