2016-11-13 69 views
-1

我有一個ResultSet對象 作爲請求表中的結果:如何將ResultSet轉換爲Restlet框架中的json對象?

ResultSet result = stat.executeQuery("SELECT * FROM Greetings"); 

我需要將它以JSON格式返回給瀏覽器。是否可以使用一些Restlet工具將ResultSet類型的變量轉換爲json對象並將其發送給Web客戶端?

+1

也許我很困惑,但也有在這個網站這麼多的問題,與結果集,以JSON的轉換處理,包括那些在[這個鏈接(HTTPS發現: //www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+resultset+to+json)。 –

回答

3

您可以使用以下函數將resultSet轉換爲jsonArray並將其發送到您的瀏覽器。

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

private JSONArray convertToJSON(ResultSet resultSet) 
     throws Exception { 
    JSONArray jsonArray = new JSONArray(); 

    while (resultSet.next()) { 
     int total_rows = resultSet.getMetaData().getColumnCount(); 
     JSONObject obj = new JSONObject(); 
     for (int i = 0; i < total_rows; i++) { 
      obj.put(resultSet.getMetaData().getColumnLabel(i+1) 
        .toLowerCase(), resultSet.getObject(i + 1)); 
     } 
     jsonArray.put(obj); 
    } 

    return jsonArray; 
} 
+0

請讓我問一下這個答案是否不夠。我會根據您的要求更新我的答案。 –

0

您可以使用/ jackson/databind/ObjectMapper類將Java對象轉換爲JSON。

ObjectMapper mapper = new ObjectMapper(); 

    Greetings greetings = new Greetings(); 

    //Object to JSON in file 
    mapper.writeValue(new File("c:\\file.json"), greetings); 

    //Object to JSON in String 
    String jsonInString = mapper.writeValueAsString(greetings); 

Maven的POM依賴

<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
</dependency>