如何使用Groovy Builder生成一个数组类型JSON?(How to use groovy

2019-07-17 11:05发布

我们可以通过生成Groovy的JSON建设者的对象类型JSON:

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

我喜欢这种类型的语法,而是如何建立一个数组类型JSON?

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

我发现了一些文件,其中说我们应该用JsonBuilder()构造函数:

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

但我更喜欢第一种语法。 它是能够使用它产生数组类型JSON?

Answer 1:

你提出的语法看起来并不可能,因为我不相信它是有效的时髦。 闭包,如{"blah":"foo"}不有意义的常规,而你要通过语法限制的约束。 我认为你要能够做到最好的是以下中的内容:

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


Answer 2:

还可以创建关闭的名单,并通过它与助洗剂

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


Answer 3:

我喜欢在年底超过建设者转换,

def json = [ 
            profile: [
                      _id: profile._id,
                      fullName: profile.fullName,
                      picture: profile.picture
                     ]
            ,title: title
            ,details: details
            ,tags: ["tag1","tag2"]
            ,internalTags: ["test"]
            ,taggedProfiles: []
           ] as JSON


文章来源: How to use groovy builder to generate an array-type json?