8.1.6 XML and JSON Responses - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.1.4
8.1.6 XML and JSON Responses
Using the render method to output XML
Grails supports a few different ways to produce XML and JSON responses. The first is the render method.Therender method can be passed a block of code to do mark-up building in XML:def list() {    def results = Book.list()    render(contentType: "text/xml") {
        books {
            for (b in results) {
                book(title: b.title)
            }
        }
    }
}<books> <book title="The Stand" /> <book title="The Shining" /> </books>
def list() {    def books = Book.list()  // naming conflict here    render(contentType: "text/xml") {
        books {
            for (b in results) {
                book(title: b.title)
            }
        }
    }
}books which Groovy attempts to invoke as a method.Using the render method to output JSON
Therender method can also be used to output JSON:def list() {    def results = Book.list()    render(contentType: "application/json") {
        books = array {
            for (b in results) {
                book title: b.title
            }
        }
    }
}[
    {"title":"The Stand"},
    {"title":"The Shining"}
]Automatic XML Marshalling
Grails also supports automatic marshalling of domain classes to XML using special converters.To start off with, import thegrails.converters package into your controller:import grails.converters.*render Book.list() as XML
<?xml version="1.0" encoding="ISO-8859-1"?> <list> <book id="1"> <author>Stephen King</author> <title>The Stand</title> </book> <book id="2"> <author>Stephen King</author> <title>The Shining</title> </book> </list>
Automatic JSON Marshalling
Grails also supports automatic marshalling to JSON using the same mechanism. Simply substituteXML with JSON:render Book.list() as JSON
[
    {"id":1,
     "class":"Book",
     "author":"Stephen King",
     "title":"The Stand"},
    {"id":2,
     "class":"Book",
     "author":"Stephen King",
     "releaseDate":new Date(1194127343161),
     "title":"The Shining"}
 ]