我在使用JsonBuilder时遇到了两个问题。我通过研究尝试了一切。这是我最接近解决这个问题的方法,但这不对。
这是建筑物
def root = builder.output {
days {
for (Day day : model.days) {
"$day.name" {
agendas {
for (Agenda agenda : day.agendas) {
"$agenda.name" {
name agenda.name
}
}
}
}
}
}
}
JSON
{ "output": {
"days": {
"Day 1": {
"agendas": {
"Day 2 Agenda B": {
"name": "Day 2 Agenda A"
},
"Day 2 Agenda A": {
"name": "Day 2 Agenda A"
}
}
},
"Day 2": {
"agendas": {
"Day 2 Agenda B": {
"name": "Day 2 Agenda A"
},
"Day 2 Agenda A": {
"name": "Day 2 Agenda A"
}
}
}
}
}}
我所追求的是:
{ "output": {
"days": [
{
"name": "Day 1",
"agendas": [
{
"name": "Day 1 Agenda A"
},
{
"name": "Day 1 Agenda B"
}
]
},
{
"name": "Day 2",
"agendas": [
{
"name": "Day 2 Agenda A"
},
{
"name": "Day 2 Agenda B"
}
]
}
]
}}
答案 0 :(得分:0)
我终于明白了:)
def builder = new JsonBuilder()
builder {
days(days.collect { day ->
[
name: day.name,
agendas: day.agendas.collect { agenda ->
name: agenda.name
}
]
})
}
答案 1 :(得分:0)
可以在没有collect()
的情况下完成:
builder.days(DAYS) { day->
name day.name
agendas(day.agendas){ agenda ->
name agenda.name
}
}
这是输出:
{
"days": [
{
"name": "Day 1",
"agendas": [
{
"name": "Day 1 Agenda A"
},
{
"name": "Day 1 Agenda B"
}
]
},
{
"name": "Day 2",
"agendas": [
{
"name": "Day 2 Agenda A"
},
{
"name": "Day 2 Agenda B"
}
]
}
]
}