# StreamingJsonBuilder

version 3.0.1

Unlike `JsonBuilder` which creates a data structure in memory, which is handy in those situations where you want to alter the structure programmatically before output, `StreamingJsonBuilder` directly streams to a writer without any intermediate memory data structure. If you do not need to modify the structure and want a more memory-efficient approach, use `StreamingJsonBuilder`.

The usage of `StreamingJsonBuilder` is similar to `JsonBuilder`. In order 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 use a `StreamingJsonBuilder` like this:

    StringWriter writer = new StringWriter()
    StreamingJsonBuilder builder = new StreamingJsonBuilder(writer)
    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(writer.toString())

We use JsonUnit to check the expected result:

    JsonAssert.assertJsonEquals(json, carRecords)

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

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

    StringWriter writer = new StringWriter()
    StreamingJsonBuilder builder = new StreamingJsonBuilder(writer, 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 writer.toString() == '{"records":{"car":{"name":"HSV Maloo","homepage":"http://groovy-lang.org"}}}'