以Grails格式呈现Json

时间:2012-09-17 11:16:22

标签: json grails

我正在做这样的事情:

def prods = Product.executeQuery("select category.id,category.name, avg(competition1Price), avg(competition2Price), avg(onlineCompetitionPrice) from Product group by category.id")
            def output = [[:]]
            prods.each { result ->
                def prod = ['category_id':result[0],'category_name':result[1],'Competition1Price':result[2],'competition2Price':result[3],'onlineCompetitionPrice':result[4]]
                output << prod
                }
            render output as JSON

我得到的输出是这样的:

 [{},{"category_id":1,"category_name":"Colchones y","Competition1Price":1657.4784,"competition2Price":2071.5,"onlineCompetitionPrice":1242.5}]

我想要的是: 像这样......

   {collection:[{"category_id":"1","category_name":"Colchones y",so on...]}

有人可以帮忙.. 如何操纵json数据的格式..

1 个答案:

答案 0 :(得分:3)

如果这是您想要的格式,您需要执行以下操作:

def prods = Product.executeQuery("select category.id,category.name, avg(competition1Price), avg(competition2Price), avg(onlineCompetitionPrice) from Product group by category.id")
def output = [collection:[]]
prods.each { result ->
    def prod = ['category_id':result[0],'category_name':result[1],'Competition1Price':result[2],'competition2Price':result[3],'onlineCompetitionPrice':result[4]]
    output.collection << prod
}
render output as JSON

或(可以说是更整洁):

def prods = Product.executeQuery("select category.id,category.name, avg(competition1Price), avg(competition2Price), avg(onlineCompetitionPrice) from Product group by category.id")
def prodlist = prods.collect { result ->
    [ 'category_id': result[0],
      'category_name': result[1],
      'Competition1Price':result[2],
      'competition2Price':result[3],
      'onlineCompetitionPrice':result[4] ]
}
render [ collection: prodlist ] as JSON