8.1.7 More on JSONBuilder - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.1.4
8.1.7 More on JSONBuilder
The previous section on on XML and JSON responses covered simplistic examples of rendering XML and JSON responses. Whilst the XML builder used by Grails is the standard XmlSlurper found in Groovy, the JSON builder is a custom implementation specific to Grails.JSONBuilder and Grails versions
JSONBuilder behaves different depending on the version of Grails you use. For version below 1.2 the deprecated grails.web.JSONBuilder class is used. This section covers the usage of the Grails 1.2 JSONBuilderFor backwards compatibility the oldJSONBuilder
class is used with the render
method for older applications; to use the newer/better JSONBuilder
class set the following in application.groovy
:grails.json.legacy.builder = false
Rendering Simple Objects
To render a simple JSON object just set properties within the context of the Closure:render(contentType: "application/json") { hello = "world" }
{"hello":"world"}
Rendering JSON Arrays
To render a list of objects simple assign a list:render(contentType: "application/json") {
categories = ['a', 'b', 'c']
}
{"categories":["a","b","c"]}
render(contentType: "application/json") { categories = [ { a = "A" }, { b = "B" } ] }
{"categories":[ {"a":"A"} , {"b":"B"}] }
element
method to return a list as the root:render(contentType: "application/json") {
element 1
element 2
element 3
}
[1,2,3]
Rendering Complex Objects
Rendering complex objects can be done with Closures. For example:render(contentType: "application/json") { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }
{"categories":["a","b","c"],"title":"Hello JSON","information":{"pages":10}}
Arrays of Complex Objects
As mentioned previously you can nest complex objects within arrays using Closures:render(contentType: "application/json") { categories = [ { a = "A" }, { b = "B" } ] }
array
method to build them up dynamically:def results = Book.list() render(contentType: "application/json") { books = array { for (b in results) { book title: b.title } } }
Direct JSONBuilder API Access
If you don't have access to therender
method, but still want to produce JSON you can use the API directly:def builder = new JSONBuilder()def result = builder.build { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }// prints the JSON text println result.toString()def sw = new StringWriter() result.render sw