Child pages
  • Using the JSONGroovyBuilder
Skip to end of metadata
Go to start of metadata

The extensions.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:

This can be simplified by using JSONGroovyBuilder's write method:

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.

produces...


produces...


produces...


produces...


produces...

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:

produces...

  • No labels