0

我有两个 ArrayList,我需要以 JSON 格式打印。我使用下面的代码将 ArrayList 打印为 JSON 字符串

def a = ['R1','R2']
def b = ['R3','R4']
def json = new groovy.json.JsonBuilder()

json set1: a
println groovy.json.JsonOutput.prettyPrint(json.toString())

json set2: b
println groovy.json.JsonOutput.prettyPrint(json.toString())

实际输出

{
    "set1": [
        "R1",
        "R2"
    ]
}

{
    "set2": [
        "R3",
        "R4"
    ]
}

它将被打印为两个 JSON 文件,但我是否需要将所有两个集合打印/组合成一个 JSON 输出?

我的预期输出

{
  "set1": [
    "R1",
    "R2"
  ],
  "set2": [
    "R3",
    "R4"
  ]
}
4

1 回答 1

1
def a=[111,222,333]
def b=[444,555,666]

def jb = new groovy.json.JsonBuilder() 
jb {
  set1(a)
  set2(b)
}
println jb.toPrettyString()

或者

println new groovy.json.JsonBuilder([ set1:a, set2:b ]).toPrettyString()
于 2021-09-21T12:23:34.783 回答