15

我们可以通过 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()

我喜欢这种类型的语法,但是如何构建一个数组类型的 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?

4

3 回答 3

8

您提出的语法看起来不可能,因为我不相信它是有效的 groovy。诸如此类的闭包{"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
   ]
)
于 2012-12-20T16:08:58.573 回答
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()
于 2014-10-07T06:32:04.530 回答
0

我最终比建造者更喜欢转换,

def json = [ 
            profile: [
                      _id: profile._id,
                      fullName: profile.fullName,
                      picture: profile.picture
                     ]
            ,title: title
            ,details: details
            ,tags: ["tag1","tag2"]
            ,internalTags: ["test"]
            ,taggedProfiles: []
           ] as JSON
于 2012-12-21T02:09:42.963 回答