2013-12-16 59 views
0

我正在写一个Grails web应用程序采取下面的输入数据,并将其重新格式化为低于输出格式则可以用来绘制fancyTree视图。我创建了一个控制器类,其代码如下所示。 我怎么能遍历做出那样的输出格式的格式如下图所示?我研究了Groovy如何进行每种语法,但我如何使用它来添加配料?Grails的创建JSON格式输出

代码摘录:

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

您是否尝试过:

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