我正在编写一个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"}
]
}
]
答案 0 :(得分:0)
你试过了吗?
for (record in results){
def ingredients = [:]
for (ingredient in record.ingredients) {
ingredients.add([title: ingredient.item_name)
}
test.add([title: results.category, ingredients: ingredients
])
}