The commons.json bundle includes a Groovy Builder which makes it easy to create JSON documents from Sling scripts. This code is inspired by the builder contained in Andres Almiray's json-lib project (http://json-lib.sourceforge.net/). However, Sling's builder is not compatible with the json-lib builder.
A basic script looks like this:
builder = new org.apache.sling.commons.json.groovy.JSONGroovyBuilder() out.write builder.json { text currentNode.getProperty("text").string } as String
Examples
These examples are taken from the test case: http://svn.apache.org/viewvc/sling/trunk/bundles/commons/json/src/test/groovy/org/apache/sling/commons/json/groovy/JSONGroovyBuilderTest.groovy?view=markup.
The JSON output below is formatted for readability. Actual output will be compact.
builder.json { }
produces...
{}
builder.json([])
produces...
[]
builder.json { string "json" integer 1 bool true }
produces...
{ 'string' : 'json', 'integer' : 1, 'bool' : true }
builder.json { first { integer 42 } second { integer 48 } }
produces...
{ 'first' : { 'integer' : 42 }, 'second' : { 'integer' : 48 } }
builder.json { books { book { title "The Definitive Guide to Grails" author "Graeme Rocher" } book { title "Groovy in Action" author "Dierk Konig" } } }
produces...
{ 'books' : { 'book' : [ { 'title' : 'The Definitive Guide to Grails', 'author' : 'Graeme Rocher' }, { 'title' : 'Groovy in Action', 'author' : 'Dierk Konig' } ] } }
Creating a Wrapper
The json
pseudo-method of JSONGroovyBuilder
produces an instance of org.apache.sling.commons.json.JSONObject
based on the parameters passed to it. If a different psuedo-method is called, the method name will be used to create a wrapper object. For example:
builder.books { book { title "The Definitive Guide to Grails" author "Graeme Rocher" } book { title "Groovy in Action" author "Dierk Konig" } }
produces...
{ 'books' : { 'book' : [ { 'title' : 'The Definitive Guide to Grails', 'author' : 'Graeme Rocher' }, { 'title' : 'Groovy in Action', 'author' : 'Dierk Konig' } ] } }