如何在Restlet框架中将ResultSet转换为json对象?

时间:2016-11-13 15:45:49

标签: java json restlet

我有一个ResultSet对象 作为对表的请求的结果:

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

我需要以json格式将其返回给浏览器。是否可以使用一些Restlet工具将ResultSet类型的变量转换为json对象并将其发送到Web客户端?

2 个答案:

答案 0 :(得分:2)

您可以使用以下函数将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;
}

答案 1 :(得分: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>
相关问题