我正在尝试生成一个包含多个嵌套对象的 JSON 数组。
这是我想要生成的内容:(由于我想要一个数组,因此缩短了输出,如果您运行代码,这只会重复):
[
{
"User": {
"Name": "Foo",
"Email": "test@example.com"
},
"Details": {
"Address": {
"City": "Anywhere",
"Country": "USA",
"State": "ID",
"ZipCode": "55842"
},
"FavoriteColor": "Blue"
}
}
]
相反,我正在生成这个:
[
{
"User": {
"Name": "Foo",
"Email": "test@example.com"
},
"Address": {
"City": "Anywhere",
"Country": "USA",
"State": "ID",
"ZipCode": "55842"
},
"Details": [
{
"FavoriteColor": "Blue"
},
{
"City": "Anywhere",
"Country": "USA",
"State": "ID",
"ZipCode": "55842"
}
]
}
]
这是我的代码:
def array = 1..3
def builder = new groovy.json.JsonBuilder()
builder array.collect { itemNumber ->
[{
User(
Name: "Foo" + itemNumber,
Email: "test@example.com"
)
Details(
Address(
City: "Anywhere",
Country: "USA",
State: "ID",
ZipCode: "55842"
),
FavoriteColor: "Blue"
)
}
]
}
println groovy.json.JsonOutput.prettyPrint(builder.toString())