将ResultSet转换为JSON使用Gson

3
如果我有这样的一个表格:
MsUser
  - userID
  - username

MsProject
  - userID
  - ProjectID
  - ProjectName

如果我有这样的查询:
Result set = select * from MsUser mu, MsProject mp WHERE mu.userID = mp.userID

我能使用Google gson将上述查询结果集转换为JSON吗?顺便说一下,我正在使用JSP开发我的应用程序。
1个回答

8
你可以使用这个方法将 ResultSet 对象转换为 jsonArray
public static JSONArray convertToJSON(ResultSet resultSet)
            throws Exception {
        JSONArray jsonArray = new JSONArray();
        while (resultSet.next()) {
            int total_columns = resultSet.getMetaData().getColumnCount();
            JSONObject obj = new JSONObject();
            for (int i = 0; i < total_columns; i++) {
                obj.put(resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase(), resultSet.getObject(i + 1));
            }
          jsonArray.put(obj);
        }
        return jsonArray;
    }

如果您想将此jsonArray转换为json对象,则使用以下方法:
JSONObject jsonObject = new JSONObject();
jsonObject.put("arrayName",jsonArray);

更新:要将 ResultSet 转换为 JSON 对象,我们需要使用 org.json jar。您应该下载并将其添加到项目类路径中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接