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'
      address {
        streetName 'Gordon street'
        city 'Philadelphia'
        houseNumber 20
      }
    }
    println builder.toPrettyString()
  2. The output of the previous script yields:
    {
      "customer": {
      "name": "John",
      "lastName": "Appleseed",
      "address": {
        "streetName": "Gordon street",
        "city": "Philadelphia",
        "houseNumber": 20
        }
      }
    }
  3. Here is a slightly more complex example of 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"
            }
          ]
        }
      ]
    }

How it works...

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:

  • One of the simple data type (for example, Boolean and String) permitted by JSON
  • Another Map
  • Collection of the above
  • A closure or a collection of closures

To demonstrate the flexibility of JsonBuilder in our example, we used different types, including closures.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.141.75