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.
The following steps will show some examples of using JsonBuilder
.
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()
{ "customer": { "name": "John", "lastName": "Appleseed", "address": { "streetName": "Gordon street", "city": "Philadelphia", "houseNumber": 20 } } }
JsonBuilder
usage, used to build the definition of a chart widget:def chart = [ items: [ type: 'chart', height: 200, width: 300, axes: [ { type 'Time' fields ([ 'x' ]) position 'left' title 'Time' }, { type 'Numeric' fields ( [ 'y' ] ) position 'bottom' title 'Profit in EUR' } ] ] ] def builder = new JsonBuilder(chart) println builder.toPrettyString()
The output of the previous statement is: { "items": [ { "type": "chart", "height": 200, "width": 300, "axes": [ { "type": "Time", "fields": [ "x" ], "position": "left", "title": "Time" }, { "type": "Numeric", "fields": [ "y" ], "position": "bottom", "title": "Profit in EUR" } ] } ] }
JsonBuilder
can produce JSON-formatted output from Maps, Lists, and Java Beans (see the Converting JSON message to Groovy Bean recipe). The output is stored in memory, and it can be written to a stream or processed further. If we want to directly stream (instead of storing it in memory) the data as it's created, we can use StreamingJsonBuilder
instead of the JsonBuilder
.
In the example at step 1, we create an instance of the JsonBuilder
class and we simply define the key/value pairs that contain the data structure we wish to create. The approach is very similar to any other builder, such as MarkupBuilder
(see the Constructing XML content recipe in Chapter 5, Working with XML in Groovy).
In the second example, the builder is directly created by passing a variable containing a Map
. The Map
's keys are Strings
as defined by the JSON standard, but the assigned values can be one of the following types:
Boolean
and String
) permitted by JSONMap
To demonstrate the flexibility of JsonBuilder
in our example, we used different types, including closures.