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 Lists and Maps 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.

  1. 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' ...

Get Groovy 2 Cookbook 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.