How to use groovy builder to generate an array-typ

2019-02-08 08:56发布

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?

3条回答
爷的心禁止访问
2楼-- · 2019-02-08 09:27

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()
查看更多
该账号已被封号
3楼-- · 2019-02-08 09:27

I like conversion in the end more than builder,

def json = [ 
            profile: [
                      _id: profile._id,
                      fullName: profile.fullName,
                      picture: profile.picture
                     ]
            ,title: title
            ,details: details
            ,tags: ["tag1","tag2"]
            ,internalTags: ["test"]
            ,taggedProfiles: []
           ] as JSON
查看更多
小情绪 Triste *
4楼-- · 2019-02-08 09:38

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
   ]
)
查看更多
登录 后发表回答