【问题标题】:Grails Creating JSON format outputGrails 创建 JSON 格式输出
【发布时间】:2013-12-16 08:11:57
【问题描述】:

我正在编写一个 Grails Web 应用程序来获取下面的输入数据并将其重新格式化为下面的输出格式,然后可以用来绘制 fancyTree 视图。我创建了一个控制器类,代码如下所示。 如何迭代以使格式类似于下面显示的输出格式?我查看了 Groovy 是如何处理每种语法的,但我如何使用它来添加成分?

代码摘录:

def list(){

    def results = recipies.list()

    def recipiesContents = [:] //Test List

    recipiesContents=[] 

    for (record in results){
        test.add([folder:true, title: results.Name, key: results.key
        ])
    }


    //render response types
    withFormat {
        html test
        json {render test as JSON}
        xml {render test as XML}
    }
}

输入数据:

{
recipies :[

{key: "1",
category:"Tuna Sandwich"
data:[{some data}],
ingredients: [
    {item_name:"mayo",
      brand: "My Own Brand"
    },
    {
      item_name: "Tuna".
      brand: "Bumble Bee"
    }
]},
{key: "2",
category:"Chicken Noodle Soup"
data:[{some data}],
ingredients: [
    {item_name:"condensed chicken soup",
      brand: "Campbell"
    },
    {
      item_name: "Noodles".
      brand: "Top Ramen"
    }
]}

]
}

输出数据:

[
{
    title: "Tuna Sandwich"
    ingredients: [
        {title: "Tuna"},
        {title: "mayo"}
    ]
},
{
    title: "Chicken Noodle Soup",
    ingredients: [
        {title: "condensed chicken soup"},
        {title: "Noodles"}
    ]
}
]

【问题讨论】:

    标签: json grails


    【解决方案1】:

    你试过了吗:

    for (record in results){
        def ingredients = [:]
        for (ingredient in record.ingredients) {
            ingredients.add([title: ingredient.item_name)
        }
        test.add([title: results.category, ingredients: ingredients
        ])
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-22
      • 1970-01-01
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 2020-07-24
      • 2017-01-16
      相关资源
      最近更新 更多