2016-11-13 124 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>