How to use groovy builder to generate an array-type json?

Freewind picture Freewind · Dec 20, 2012 · Viewed 14.4k times · Source

We can generate an object-type json by groovy's json builder:

def builder = new groovy.json.JsonBuilder()
def root = builder.people {
    person {
        firstName 'Guillame'
        lastName 'Laforge'
        // Named arguments are valid values for objects too
        address(
               city: 'Paris',
               country: 'France',
               zip: 12345,
        )
        married true
        // a list of values
        conferences 'JavaOne', 'Gr8conf'
    }
}
def jsonStr = builder.toString()

I like this type of syntax, but how to build an array-type json?

E.g.

[
    {"code": "111", "value":"222"},
    {"code": "222", "value":"444"}
]

I found some documents which say we should use JsonBuilder() constructor:

def mydata = [ ["code": "111", "value":"222"],["code": "222", "value":"444"] ]
def builder = new groovy.json.JsonBuilder(mydata)
def jsonStr = builder.toString()

But I preferred the first syntax. Is it able to use it generate array-type json?

Answer

Brian Henry picture Brian Henry · Dec 20, 2012

The syntax you propose doesn't look possible, as I don't believe it's valid groovy. A closure such as {"blah":"foo"} doesn't makes sense to groovy, and you're going to be constrained by syntactical limitations. I think the best you're going to be able to do is something within the following:

def root = builder.call (
   [
      {
        code "111"
        value "222"
      },
      {code "222"; value "444"}, //note these are statements within a closure, so ';' separates instead of ',', and no ':' used
      [code: "333", value:"555"], //map also allowed
      [1,5,7]                     //as are nested lists
   ]
)