Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
    }
}
like image 361
pixel Avatar asked Jan 28 '23 11:01

pixel


2 Answers

You can write something like below:

def json = new groovy.json.JsonBuilder()
json  { 
  root (
   [
       {
        key ('color')
        value ('orange')
     }
   ]
  )
}

println json.toPrettyString()

Notice how array is passed to root in the above.

like image 155
Rao Avatar answered Jan 31 '23 01:01

Rao


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"
        }
    ]
}
like image 41
Szymon Stepniak Avatar answered Jan 31 '23 01:01

Szymon Stepniak