Groovy 2 JsonBuilder嵌套的可迭代关联

时间:2012-10-30 17:11:20

标签: json groovy

我在使用JsonBuilder时遇到了两个问题。我通过研究尝试了一切。这是我最接近解决这个问题的方法,但这不对。

  1. 日期和议程的数组没有特征 - 它们是非数组的。
  2. 由于某种原因,第2天的议程数据将在第1天的议程结构中公布。基础数据是正确的。
  3. 这是建筑物

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

2 个答案:

答案 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"
                }
            ]
        }
    ]
}