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

旧街凉风 提交于 2019-11-29 17:49:19

问题


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?


回答1:


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
   ]
)



回答2:


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:


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


来源:https://stackoverflow.com/questions/13973342/how-to-use-groovy-builder-to-generate-an-array-type-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!