Grails Converters Reference
The Converters aim to give you the ability to quickly transform any kind of Java/Groovy Objects to JSON/XML
The Converter Classes
Currently, there are 4 classes that can be used as Converters:
- for JSON Conversion
- grails.converters.JSON
- grails.converters.deep.JSON
- for XML Conversion
- grails.converters.XML
- grails.converters.deep.XML
The default Converters (in the grails.converter package) render Domainclass associations as ID's, while the Deep Converters (in the grails.converters.deep package) also fully render the associations (nested domainclass instances) and also handle circular relations.
Initializing a Converter
To create a converter instance you have to choose from one the following notations:
default initialization
def converter = new JSON(target: Book.list());
Constructs a new instance of the JSON Converter and sets the target property to the object which should get converted.
the "as" operator
def converter = Book.list() as JSON
Same as the example above using a neat syntax.
Using a Converter Instance
What can you do, when you have successfully created a converter instance?
toString()
Calling toString on a Converter instance performs the conversion of the target and constructs a String containing the resulting JSON/XML.
def converter = Book.get(1) as JSON;
println converter.toString();
rendering to a java.io.Writer
The render method of Converters can take any java.io.Writer
def converter = Book.list() as XML
converter.render(new java.io.FileWriter("/path/to/my/file.xml"));
rendering to a HttpServletResponse
You can use a Converter to render the result directly to a HttpServletResponse. The Converter will also set the appropriate Content-Type Header. The following example illustrated two ways to achieve that:
import grails.converters.*;
class AjaxController {
def list1 = {
def converter = Book.list() as JSON
converter.render(response) return false
}
def list2 = {
render Book.list() as JSON }
def xmllist = {
render Book.list as XML
}
}
Codecs
encodeAsJSON
encodeAsXML
Reverse Conversion
parse(String)
parse(InputStream)
parse(HttpServletRequest)
request.XML and request.JSON