Constructing JSON messages with JsonBuilder
This recipe provides an overview of another class introduced in Groovy 1.8, which helps to construct JSON messages, the JsonBuilder
.
This class works like any other builder class in Groovy (see the Defining data structures as code in Groovy recipe from Chapter 3, Using Groovy Language Features). A data structure based on List
s and Map
s is defined, and JSON is split out when the string representation is requested.
How to do it...
The following steps will show some examples of using JsonBuilder
.
Let's start right away with a simple script that builds the representation of a fictional customer:
import groovy.json.JsonBuilder def builder = new JsonBuilder() builder.customer { name 'John' lastName 'Appleseed' address { streetName 'Gordon street' city 'Philadelphia' houseNumber 20 } } println builder.toPrettyString()
The output of the previous script yields:
{ "customer": { "name": "John", "lastName": "Appleseed", "address": { ...