The commonsextensions.json groovy 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.
An instance of this class is available to all Groovy scripts as a variable named jsonBuilder
.
A basic script looks like this:
Code Block |
---|
builder = new org.apache.sling.commons.json.groovy.JSONGroovyBuilder() out.write builderjsonBuilder.json { text currentNode.getProperty("text").string } as String |
This can be simplified by using JSONGroovyBuilder
's write
method:
Code Block |
---|
jsonBuilder.write(out).json {
}
|
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.
Note |
---|
The JSON output below is formatted for readability. Actual output will be compact. |
Code Block |
---|
builderjsonBuilder.json { } |
produces...
Code Block |
---|
{} |
...
Code Block |
---|
builderjsonBuilder.json([]) |
produces...
Code Block |
---|
[] |
...
Code Block |
---|
builderjsonBuilder.json { string "json" integer 1 bool true } |
...
Code Block |
---|
{ 'string' : 'json', 'integer' : 1, 'bool' : true } |
...
Code Block |
---|
builderjsonBuilder.json { first { integer 42 } second { integer 48 } } |
...
Code Block |
---|
{ 'first' : { 'integer' : 42 }, 'second' : { 'integer' : 48 } } |
...
Code Block |
---|
builderjsonBuilder.json { books { book { title "The Definitive Guide to Grails" author "Graeme Rocher" } book { title "Groovy in Action" author "Dierk Konig" } } } |
...
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:
Code Block |
---|
builder.books {
book {
title "The Definitive Guide to Grails"
author "Graeme Rocher"
}
book {
title "Groovy in Action"
author "Dierk Konig"
}
}
|
produces...
Code Block |
---|
{
'books' : {
'book' : [
{ 'title' : 'The Definitive Guide to Grails', 'author' : 'Graeme Rocher' },
{ 'title' : 'Groovy in Action', 'author' : 'Dierk Konig' }
]
}
}
|