# JsonBuilder

version 2.5.13

Groovy’s `JsonBuilder` makes it easy to create Json. For example to create this Json string:

    String carRecords = '''
        {
            "records": {
            "car": {
                "name": "HSV Maloo",
                "make": "Holden",
                "year": 2006,
                "country": "Australia",
                "record": {
                  "type": "speed",
                  "description": "production pickup truck with speed of 271kph"
                }
              }
          }
        }
    '''

you can use a `JsonBuilder` like this:

    JsonBuilder builder = new JsonBuilder()
    builder.records {
      car {
            name 'HSV Maloo'
            make 'Holden'
            year 2006
            country 'Australia'
            record {
                type 'speed'
                description 'production pickup truck with speed of 271kph'
            }
      }
    }
    String json = JsonOutput.prettyPrint(builder.toString())

We use JsonUnit to check that the builder produced the expected result:

    JsonAssert.assertJsonEquals(json, carRecords)

If you need to customize the generated output you can pass a `JsonGenerator` instance when creating a `JsonBuilder`:

    import groovy.json.*

    def generator = new JsonGenerator.Options()
            .excludeNulls()
            .excludeFieldsByName('make', 'country', 'record')
            .excludeFieldsByType(Number)
            .addConverter(URL) { url -> "http://groovy-lang.org" }
            .build()

    JsonBuilder builder = new JsonBuilder(generator)
    builder.records {
      car {
            name 'HSV Maloo'
            make 'Holden'
            year 2006
            country 'Australia'
            homepage new URL('http://example.org')
            record {
                type 'speed'
                description 'production pickup truck with speed of 271kph'
            }
      }
    }

    assert builder.toString() == '{"records":{"car":{"name":"HSV Maloo","homepage":"http://groovy-lang.org"}}}'