def list() {
def results = Book.list()
render(contentType: "text/xml") {
books {
for (b in results) {
book(title: b.title)
}
}
}
}
8.1.6 XML and JSON Responses
Version: 3.2.0
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.
The render
method can be passed a block of code to do mark-up building in XML:
The result of this code would be something like:
<books>
<book title="The Stand" />
<book title="The Shining" />
</books>
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)
}
}
}
}
This is because 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: "application/json") {
books(results) { Book b ->
title b.title
}
}
}
In this case the result would be something along the lines of:
[
{"title":"The Stand"},
{"title":"Shining"}
]
This technique for rendering JSON may be ok for very simple responses, but in general you should favour the use of JSON Views and use the view layer rather than embedding logic in your application. |
The same dangers with naming conflicts described above for XML also apply to JSON building.
Automatic XML Marshalling
Grails also supports automatic marshalling of domain classes to XML using 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>
For more information on XML marshalling see the section on REST
Automatic JSON Marshalling
Grails also supports automatic marshalling to JSON using the same mechanism. Simply substitute XML
with JSON
:
render Book.list() as JSON
The resulting output would look something like the following:
[
{"id":1,"author":"Stephen King","title":"The Stand"}
{"id":2,"author":"Stephen King","title":"The Shining"},
]
This technique for rendering JSON may be ok for very simple responses, but in general you should favour the use of JSON Views and use the view layer rather than embedding logic in your application. |