2012-01-20 76 views
1

我想從對象列表中構建一個json。到目前爲止,我只能將1個對象生成爲json。我錯過了什麼?有沒有更好的方法將對象列表轉換爲json?從groovy中的對象列表生成json

private static List<ProductAlertsResponse> executeSelection(String query) 
{ 
    List<ProductAlertsResponse> prodAlerts=new ArrayList<ProductAlertsResponse>() 
    sql.eachRow(query) 
    { 
     ProductAlertsResponse prodAlert=new ProductAlertsResponse((String)it.id,(String)it.name,(String)it.description,(String)it.active,(String)it.release_date) 

     //I was converting it into a List before, but then I thought it would be better to do with list of classes 
     /*String[] rows=new String[5] 
     rows[0]=(String)it.id 
     rows[1]=(String)it.name 
     rows[2]=(String)it.description 
     rows[3]=(String)it.active 
     rows[4]=(String)it.release_date 

     result.add(rows)*/ 

/*Also feel free to comment is this right way to put in list (above commented code)*/ 

     prodAlerts.add(prodAlert) 
    } 
    return prodAlerts 
} 

static main(args) { 
    AppProperties.load() 
    sql= Sql.newInstance("jdbc:oracle:thin:@"+AppProperties.get("hostname")+":"+AppProperties.get("port")+":"+AppProperties.get("service"), AppProperties.get("username"), AppProperties.get("password"),"oracle.jdbc.OracleDriver") 

    List result=executeSelection("select ID,NAME,DESCRIPTION,ACTIVE,RELEASE_DATE from productinfo where ACTIVE='A'") 

    def builder = new groovy.json.JsonBuilder() 

    def root=builder.response{ 

     product_alerts{ 
      result.each{ 
       //JsonOutput.toJson(it) 
       id it.getId() 
       name it.getName() 
       description it.getDescription() 
       active it.getActive() 
      } 

     } 

    } 
    println builder.toPrettyString() 
} 

我的輸出

{ 
    "response": { 
     "product_alerts": { 
      "id": "6", 
      "name": "ABC1", 
      "description": "Test2", 
      "active": "A" 
     } 
    } 
} 

回答

6

使用def builder = new groovy.json.JsonBuilder(result)

更新

試試這個

def json = new groovy.json.JsonBuilder() 
def result1 = json { 
    response result 
} 
println json.toPrettyString() 
+0

謝謝..在至少現在是將所有對象轉換成json。如果我想要一個根標籤「響應」會怎樣? – abi1964

+1

只是一個提示,如果您只需添加根節點,另一種方法是使用:'new groovy.json.JsonBuilder([response:result])'。 – OverZealous

+0

@OverZealous:非常感謝提示,也可以請看看繼續[這裏的問題](http://stackoverflow.com/questions/8969545/why-do-i-keep-getting-object-reference-on -server-而-IT-作品,細上一本地)? – abi1964