(Quick Reference)

10.1.8.5 JSON Views by Convention - Reference Documentation

Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari

Version: 3.1.4

10.1.8.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:

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

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 ty 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:

@Transactional
def save(Book book) {
    if (book.hasErrors()) {
        transactionStatus.setRollbackOnly()
        respond book.errors
    }    
    else {
        // valid object
    }
}

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 README and documentation included with the Github project.