2016-09-21 33 views
1

這可能很簡單,但我無法弄清楚。需要按以下方式從以下結果集形成JSON響應

這是我從數據庫接收的ResultSet。

Name  Method  Value 
Website  Online  450 
Website  Offline  500 
Mobile  Online  100 
Mobile  Offline  600 

我需要以下面的JSON格式發送響應到前端。

response: [ 
     { 
      "Name" : "Website", 
      "Online" : 450, 
      "Offline" : 500 
     }, 
     { 
      "Name" : "Mobile", 
      "Online" : 100, 
      "Offline" : 600 
     } 
] 

我需要在一個循環中形成該JSON,最好是在讀取ResultSet本身時。什麼是實現這一目標的最佳途徑。 在此先感謝。

P.S:查詢已經是一個複雜的問題,因此無法調整表的性能問題。上面的ResultSet是一個示例,結果集中可能有數百條記錄

更新: 我不確定以下解決方案的效率如何,但它有效。

Map<String, Map<String, Object>> objectMap = new LinkedHashMap<String,Map<String, Object>>(); 
Map<String, Object> map; 
    while(rs.next()){ 
    if(objectMap.containsKey(rs.getString("Name"))){ 
     map = objectMap.get(rs.getString("Name")); 
     map.put(rs.getString("Method"), rs.getInt("Value")); 
    } 
    else { 
     map = new HashMap<String, Object>(); 
     map.put("Tag", 0); 
     map.put("Plate", 0); 
     map.put("Name", rs.getString("Name")); 
     map.put(rs.getString("Method"), rs.getInt("Value")); 
    } 
    objectMap.put(rs.getString("Name"), map); 
} 

return objectMap.values(); 
+0

您可以在「答案」下發布您的解決方案並自行接受。 –

+0

@ BenediktS.Vogler做到了!謝謝。! – Naveen

回答

0
Map<String, Map<String, Object>> objectMap = new LinkedHashMap<String,Map<String, Object>>(); 
Map<String, Object> map; 
while(rs.next()){ 
    if(objectMap.containsKey(rs.getString("Name"))){ 
     map = objectMap.get(rs.getString("Name")); 
     map.put(rs.getString("Method"), rs.getInt("Value")); 
    } 
    else { 
     map = new HashMap<String, Object>(); 
     map.put("Tag", 0); 
     map.put("Plate", 0); 
     map.put("Name", rs.getString("Name")); 
     map.put(rs.getString("Method"), rs.getInt("Value")); 
    } 
    objectMap.put(rs.getString("Name"), map); 
} 

return objectMap.values(); 
0

我真的不知道你想用什麼JSON庫,但......

JSONArray jarray = new JSONArray(); 
for (Result result : results) { 
    JSONObject obj = new JSONObject(); 
    obj.put("Name", result.name); 
    obj.put("Method", result.method); 
    obj.put("Value", result.value); 
    jarray.put(obj); 
} 

不能確定,如果這是你的要價。

+0

感謝您的迴應。但是,這並不是我所要求的,但我找到了一個解決方案並對其進行了更新。 – Naveen