Converters Plugin

Last updated by patsimon 1 year ago

Grails Converters Plugin

The grails-converters plugin aims to give you the ability to convert your domain objects, maps and lists to JSON or XML very quickly, using a neat syntax.

Current Version

Version 0.3

Built for Grails 0.5.6

Installation

Starting with Grails 0.6 there is no need to install the Converters plugin. It is allready included in the core release (if you actually do run the install plugin command - the converter plug-in will fail).
$ grails install-plugin converters
$ grails clean
$ grails dev package

Basic Usage

The plugin leverages the the groovy "as" operator and extends the render method in grails controllers to directly send the result to the output stream.

render Book.get(1) as XML
will set "text/xml" as Content-Type for the response and send something like that as response content:
<?xml version="1.0" encoding="UTF-8"?>
<book id="1">
   <title>The Definite Guide to Grails</title>
   <author>
       <author id="3" />
   </author>
   <isbn>1234-6876-4532</isbn>
</book>
the same using JSON as converter:
render Book.get(1) as JSON
will set "text/json" as Content-Type and something like that as body:
{
  "id": 1,
  "title": "The Definite Guide to Grails",
  "author": 3,
  "isbn": "1234-6876-4532",
}
You have to import the converter class, you are about to use from the grails.converters package in your controller:
import grails.converters.*
or
import grails.converters.XML
or
import grails.converters.JSON

Codecs (Since 0.2)

myDomainObject.encodeAsJSON()
myDomainObject.encodeAsXML()
Can be used in views too

Examples

This is an example to render domain objects for an ext grid (http://www.extjs.com) as JSON:

def list = {
         def listResult = [ total: Book.count(), items: Book.list(params)]
         render listResult as JSON
}