Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 658
Freewind Avatar asked Dec 20 '12 13:12

Freewind


People also ask

How do you write an array of objects in JSON?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.

What is groovy JSON JsonSlurper?

JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String . The class comes with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and others.

What is JSON builder?

public interface JsonObjectBuilder. A builder for creating JsonObject models from scratch. This interface initializes an empty JSON object model and provides methods to add name/value pairs to the object model and to return the resulting object.


2 Answers

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
   ]
)
like image 181
Brian Henry Avatar answered Sep 28 '22 05:09

Brian Henry


it is also possible to create list of closures and pass it to builder

import groovy.json.*

dataList = [
    [a:3, b:4],
    [a:43, b:3, c:32]
]
builder = new JsonBuilder()
builder {
    items dataList.collect {data ->
        return {
            my_new_key ''
            data.each {key, value ->
                "$key" value
            }
        }
    }
}
println builder.toPrettyString()
like image 21
Sam Sol Avatar answered Sep 28 '22 05:09

Sam Sol