Java Reference
In-Depth Information
The JsonBuilder class can be used with lists, maps, or methods. For example, here's a
trivial list:
import groovy.json.JsonBuilder;
def builder = new JsonBuilder()
def result = builder 1,2,3
assert result == [1, 2, 3]
This builder takes a list of numbers as an argument and builds a JSON object containing
them. Here's an example of using a map:
result = builder {
first 'Fred'
last 'Flintstone'
}
assert builder.toString() == '{"first":"Fred","last":"Flintstone"}'
The result is a standard JSON object (contained in braces), whose properties are the strings
provided in the builder.
In the builder syntax you can use parentheses to build a contained object, so let's continue
on with the example:
result = builder.people {
person {
first 'Herman'
last 'Munster'
address(street:'1313 Mockingbird Lane',
city:'New York',state:'NY')
wife 'Lily'
age 34
kids 'Eddie','Marilyn'
}
}
assert builder.toString() ==
'{"people":{"person":{"first":"Herman","last":"Munster",' +
'"address":{"street":"1313 Mockingbird Lane",' +
'"city":"New York","state":"NY"},"wife":"Lily","age":34,' +
"kids":["Eddie","Marilyn"]}}}'
The generated JSON can get difficult to read, so the class adds a toPrettyString ()
method:
println builder.toPrettyString()
Search WWH ::




Custom Search