I'm trying to generate a JSON array with multiple nested objects.
Here's what I'd like to generate: (shortened output since I want an array, this just repeats if you run the code):
[
{
"User": {
"Name": "Foo",
"Email": "test@example.com"
},
"Details": {
"Address": {
"City": "Anywhere",
"Country": "USA",
"State": "ID",
"ZipCode": "55842"
},
"FavoriteColor": "Blue"
}
}
]
Instead I'm generating this:
[
{
"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"
}
]
}
]
Here's my code:
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())