Building JSON

Groovy provides convenient solutions for when we’re creating web services and need to generate a JSON-formatted object.[36] Its as simple as sending our instances to groovy.json.JsonBuilder’s constructor, and the builder takes care of the rest. We can write the generated JSON format to a Writer by calling the writeTo method, as in the next example.

UsingBuilders/BuildJSON.groovy
 
class​ Person {
 
String​ first
 
String​ last
 
def​ sigs
 
def​ tools
 
}
 
john = ​new​ Person(first: ​"John"​, last: ​"Smith"​,
 
sigs: [​'Java'​, ​'Groovy'​], tools: [​'script'​: ​'Groovy'​, ​'test'​: ​'Spock'​])
 
bldr = ​new​ groovy.json.JsonBuilder(john)
 
writer = ​new​ ​StringWriter​()
 
bldr.writeTo(writer)
 
println writer

The builder uses the ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.