Using the render method to output XML
Grails' supports a few different ways to produce XML and JSON responses. The first one covered is via the
render method.
The
render
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)
}
}
}
}
The result of this code would be something like:
<books>
<book title="The Stand" />
<book title="The Shining" />
</books>
Note that you need to be careful to avoid naming conflicts when using mark-up building. For example this code would produce an error:
def list = {
def books = Book.list() // naming conflict here
render(contentType:"text/xml") {
books {
for(b in results) {
book(title:b.title)
}
}
}
}
The reason is that there is local variable
books
which Groovy attempts to invoke as a method.
Using the render method to output JSON
The
render
method can also be used to output JSON:
def list = {
def results = Book.list()
render(contentType:"text/json") {
books = array {
for(b in results) {
book title:b.title
}
}
}
}
In this case the result would be something along the lines of:
[
{title:"The Stand"},
{title:"The Shining"}
]
Again the same dangers with naming conflicts apply to JSON building.
Automatic XML Marshalling
Grails also supports automatic marshaling of
domain classes to XML via special converters.
To start off with import the
grails.converters
package into your controller:
import grails.converters.*
Now you can use the following highly readable syntax to automatically convert domain classes to XML:
render Book.list() as XML
The resulting output would look something like the following::
<?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>
An alternative to using the converters is to use the
codecs feature of Grails. The codecs feature provides
encodeAsXML and
encodeAsJSON methods:
def xml = Book.list().encodeAsXML()
render xml
For more information on XML marshaling see the section on
RESTAutomatic JSON Marshalling
Grails also supports automatic marshaling to JSON via the same mechanism. Simply substitute
XML
with
JSON
:
render Book.list() as JSON
The resulting output would look something like the following:
[
{"id":1,
"class":"Book",
"author":"Stephen King",
"title":"The Stand"},
{"id":2,
"class":"Book",
"author":"Stephen King",
"releaseDate":new Date(1194127343161),
"title":"The Shining"}
]
Again as an alternative you can use the
encodeAsJSON
to achieve the same effect.