如何使用groovy builder生成数组类型的json?

Fre*_*ind 14 groovy jsonbuilder

我们可以通过groovy的json builder生成一个对象类型的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()
Run Code Online (Sandbox Code Playgroud)

我喜欢这种类型的语法,但是如何构建一个数组类型的json?

例如

[
    {"code": "111", "value":"222"},
    {"code": "222", "value":"444"}
]
Run Code Online (Sandbox Code Playgroud)

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

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

但我更喜欢第一种语法.是否能够使用它生成数组类型的json?

Bri*_*nry 7

你提出的语法看起来不太可能,因为我不相信它是有效的常规.一个封闭,如{"blah":"foo"}groovy没有意义,你将受到语法限制的限制.我认为你能做的最好的事情是以下内容:

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
   ]
)
Run Code Online (Sandbox Code Playgroud)