arraysjsongroovyjsonbuilder

How to create an array with a JsonBuilder in groovy


I would like to use closure way to make following json:

{
    "root": [
        {
            "key": "testkey",
            "value": "testvalue"
        }
    ]
}

I'm using following syntax:

new JsonBuilder().root {
        'key'(testKey)
        'value'(testValue)
}

But it produces:

{
    "root": {
        "key": "testkey",
        "value": "testvalue"
    }
}

Solution

  • Your example works correctly, because you pass a simple map for root key. You have to pass a list instead do produce expected output. Consider following example:

    import groovy.json.JsonBuilder
    
    def builder = new JsonBuilder()
    builder {
        root((1..3).collect { [key: "Key for ${it}", value: "Value for ${it}"] })
    }
    
    println builder.toPrettyString()
    

    In this example we pass a list of elements created with (1..3).collect {} to a root node. We have to split initialization from building a JSON body, because things like new JsonBuilder().root([]) or even builder.root([]) throw an exception, because there is no method that expects a parameter of type List. Defining list for node root inside the closure solves this problem.

    Output

    {
        "root": [
            {
                "key": "Key for 1",
                "value": "Value for 1"
            },
            {
                "key": "Key for 2",
                "value": "Value for 2"
            },
            {
                "key": "Key for 3",
                "value": "Value for 3"
            }
        ]
    }