0

JsonBuilder 有 2 个问题。我已经通过研究尝试了一切。这是我最接近解决这个问题的方法,但这是不对的。

  1. 几天的数组和议程没有特色 - 它们以非数组的形式出现。
  2. 出于某种原因,第 2 天的议程数据会出现在第 1 天的议程结构中。基础数据是正确的。

这里是建筑

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"
                }
            ]
        }
    ]
}}
4

2 回答 2

0

我终于明白了:)

    def builder = new JsonBuilder()

    builder {
        days(days.collect { day ->
            [
                name: day.name,
                agendas: day.agendas.collect { agenda ->
                    name: agenda.name   
                }
            ]
        })
    }
于 2012-10-30T18:49:33.057 回答
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"
                }
            ]
        }
    ]
}
于 2017-03-03T17:48:09.230 回答