Tech Note: Scaffolding JSON with Grails
{ Dan Stieglitz // Groovy/Grails // April 02, 2008 }
For the uninitiated, JSON “is a lightweight data-interchange format,” as humbly posted on JSON.org. It’s useful for architects in search of a lighter-than-XML transport or JavaScript developers who want service providers sending them easy to use objects for use in their pages. Grails has out-of-the-box JSON support via the JSONObject library, as well as through their converters “plugin” (which is now included in the core distribution). Converting grails domain objects to JSON (or XML, for the enthusiast) is as complicated as
render myDomainObject as JSON
and
render myDomainObject as XML
This is fantastic, and to include a JSON service in your app, you would simply add a method to your controller as such:
def json = {
if(!params.max) params.max = 10
render MyDomainObject.list( params ) as JSON
}
It doesn’t get better for the lazy developer, unless you want Grails to automatically add this method to each scaffolded controller class you generate. This is possible by customizing Grails’ scaffolding templates. First, install the templates by issuing
grails install-templates
at your project’s root. This will create the src/templates directory where the artifact and scaffold templates live. Crack open the src/templates/scaffolding/Controller.groovy file and add the following closure template:
def json = {
if(!params.max) params.max = 10
render ${className}.list( params ) as JSON
}
It’s essentially a copy of the list closure, except the controller will render a JSON string instead of passing a list to the view. You’ll also need to import the JSON converter so add this to the import section of the template:
import grails.converters.JSON;
That’s it, and the next time you generate a controller for one of your domain objects you can get a JSON list by hitting the /MyApp/MyDomainObject/json URL.
@see http://www.grails.org/Artifact+and+Scaffolding+Templates
@see http://www.json.org/
2 comments