【问题标题】:resultset to json using gson [duplicate]使用gson将结果集转换为json [重复]
【发布时间】:2016-08-02 10:18:12
【问题描述】:

如果我有这样的表:

MsUser
  - userID
  - username

MsProject
  - userID
  - ProjectID
  - ProjectName

如果我有这样的查询:

Result set = select * from MsUser mu, MsProject mp WHERE mu.userID = mp.userID

我可以使用Google gson 将上面查询的结果集转换为 JSON 吗? 顺便说一句,我使用 JSP 开发我的应用程序。

【问题讨论】:

    标签: java json jsp servlets gson


    【解决方案1】:

    您可以使用此方法将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。您应该下载并添加到您的项目类路径中。

    【讨论】:

    • 不知道为什么投反对票。
    猜你喜欢
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多