如何嵌套groovy sql结果集并为其生成JSON?

时间:2018-06-05 03:08:40

标签: sql groovy

在我的数据库中,我有订单和相应的行。我想使用groovy为每个订单生成JSON,并在下面编写一段代码,但它没有按预期工作。

def OrderResultSet=conn.rows('select ORDER_NUMBER,COMPANY_NAME from ORDERS where ORDER_NUMBER=74')
OrderResultSet.each{ 
    def LineResultset=conn.rows('select * from LINE where HEADER_ID=:ORDER_NUMBER',[ORDER_NUMBER:it.ORDER_NUMBER])
}

如何链接结果集并生成JSON,如下所示:

{  
   "ORDER_NUMBER":7493767,
   "COMPANY_NAME":"WWT",
   "LINE":[  
      {  
         "HEADER_ID":7493767,
         "LINE_ID":12,
         "INSTALLSITE_ID":22,
         "TEXT":"world"
      },
      {  
         "HEADER_ID":7493767,
         "LINE_ID":11,
         "INSTALLSITE_ID":21,
         "TEXT":"hello"
      }
   ]
}

1 个答案:

答案 0 :(得分:0)

import groovy.json.JsonBuilder

def OrderResultSet=conn.rows('select ORDER_NUMBER,COMPANY_NAME from ORDERS where ORDER_NUMBER=74')
OrderResultSet.each{ 
    it.LINE=conn.rows('select * from LINE where HEADER_ID=:ORDER_NUMBER',[ORDER_NUMBER:it.ORDER_NUMBER])
}

println new JsonBuilder(OrderResultSet).toPrettyString()