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
1. Initializing Converter
To create a converter instance you can choose any one from the following notations:
default initialization
def converter = new JSON(target: Book.list());
the “as” operator
def converter = Book.list() as JSON
2. Using Converter instance
- In order to get String representation of JSON/XML result , you can use toString() on converter’s instance as shown below:
def converter = User.get(1) as JSON;
println converter.toString();
- In order to render result to a java.io.Writer, you can use render() as shown below:
def converter = User.list() as XML
converter.render(new java.io.FileWriter(“/path/to/my/file.xml”));
- In order to render result to a HttpServletResponse, you can use render() as shown below:
import grails.converters.*;
class AjaxController {
def list1 = {
def converter = User.list() as JSON
converter.render(response)
return false
}
def list2 = {
render User.list() as JSON
}
def xmllist = {
render User.list as XML
}
}
3. Codecs
The Converters plugin also provides codecsto quickly convert arbitary objects to JSON/XML without the need to import a Converter class.
- encodeAsJSON
String result = someObject.encodeAsJSON();
- encodeAsXML
String result = someObject.encodeAsXML();
4. Reverse Conversion
Both Converters have 3 different static parse methods.
- parse(String)
import grails.converters.*
import org.codehaus.groovy.grails.web.json.*;
// package containing JSONObject, JSONArray,…
def o = JSON.parse(“{ foo: ‘bar’ }”); // Parse a JSON String
assert o instanceof JSONObject
// In this case, JSON.parse returns a JSONObject instance
assert o instanceof Map // which implements the Map interface
assert o.foo == ‘bar’ // access a property
// Parse another JSON String containing a Javascript Array
def a = JSON.parse(“[ 1, 2, 3]“)
assert a instanceof JSONArray
assert a instanceof List
assert a[0] == 1
// The following works in Grails >= 1.0.5
def rootNode = XML.parse “””<foo><bar ding=”dong”></foo>”””
// Same as Groovy’s XmlSlurper.parseText(String)
assert rootNode instanceof groovy.util.slurpersupport.GPathResult
assert rootNode.bar.@ding == ‘dong’
- parse(InputStream, String)
Both Converters feature a static method for parsing the content from an java.io.InputStream. The second parameter of this method is the character encoding to use.
import grails.converters.*
def json = JSON.parse(new FileInputStream(“/path/to/file.json”), “UTF-8″)
def xml = XML.parse(new FileInputStream(“/path/to/file.xml”), “UTF-8″)
- parse(HttpServletRequest)
A convenience method which checks the Request Content-Type, tries to detect the character encoding of the request and then parses the Request Body using the request’s inputStream.
request.XML and request.JSON
When you access request.XML or request.JSON the appropriate Converters’ parse method is automatically invoked which then checks the Content-Type header of the Request and in the case of a match parses the Request Body
import grails.converters.*
class SomeController {
// We assume the client requests this action using the request Content-Type
// “application/json” and { foo: ‘bar’ } as Request Body
def postJson = {
def json = request.JSON
assert json.foo == ‘bar’
}
// We assume the client requests this action using the request Content-Type
// “text/xml” and <foo><bar ding=”dong”></foo> as Request Body
def postXml = {
def xml = request.XML
assert xml.bar.@ding == ‘dong’
}
}
5. Configuration:
Example of Configuration in Config.groovy file:
grails.converters {
encoding = “ISO-8859-1″
json.date = “javascript”
default.pretty.print = true
}
6. Customizing Converters Results
You can customize which properties of class should be included in JSON representation by registering a specific Object Marshaller(grails.converters.JSON.registerObjectMarshaller) :
// a class to output in JSON
class User {
String login
String passwd
// JSON definition of the User object
static {
grails.converters.JSON.registerObjectMarshaller(User) {
// you can filter here the key-value pairs to output:
return it.properties.findAll {k,v -> k != ‘passwd’}
}
}
// a controller action
def myAction() {
def a = new User(login:’bob’, passwd:’1234′)
def list = [a, a]
render list as JSON
}
ProsperaSoft offers Grails development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Grails experts and consultants.