Java Reference
In-Depth Information
def result = slurper.parseText('{"first":"Herman","last":"Munster"}')
assert result.first == 'Herman'
assert result.last == 'Munster'
Instantiate the slurper and call its parseText method, and the result is a map that can be
accessed in the usual way, as shown. Lists work as well:
result = slurper.parseText(
'{"first":"Herman","last":"Munster","kids":["Eddie","Marilyn"]}')
assert result.kids == ['Eddie','Marilyn']
The two children wind up in an instance of ArrayList . You can also add numbers and
even contained objects:
result = slurper.parseText(
'{"first":"Herman","last":"Munster","address":{"street":"1313 Mockingbird
Lane","city":"New York","state":"NY"},"wife":"Lily",
"age":34,"kids":["Eddie","Marilyn"]}')
result.with {
assert wife == 'Lily'
assert age == 34
assert address.street == '1313 Mockingbird Lane'
assert address.city == 'New York'
assert address.state == 'NY'
}
The age becomes an integer. The address object is also parsed into a map, whose prop-
erties are also available in the standard way. Here, by the way, I used the with method,
which prepends whatever value it's invoked on to the contained expressions. wife is short
for result.wife , and so on.
If parsing is easy, building is also a simple operation, much like using MarkupBuilder .
B.9.2. Building JSON
I discussed builders earlier, and I use them throughout the topic. In various chapters I use
MarkupBuilder (shown in this chapter), SwingBuilder , and AntBuilder . Here
I'll illustrate the builder for generating JSON, called JsonBuilder .
Search WWH ::




Custom Search