Convert ResultSet to JSON and XML

 public static 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;
    }


    public static String convertToXML(ResultSet resultSet)
            throws Exception {
        StringBuilder xmlArray = new StringBuilder("<results>");
        while (resultSet.next()) {
            int total_rows = resultSet.getMetaData().getColumnCount();
            xmlArray.append("<result ");
            for (int i = 0; i < total_rows; i++) {
                xmlArray.append(" ").append(resultSet.getMetaData().getColumnLabel(i + 1)
                        .toLowerCase()).append("='").append(resultSet.getObject(i + 1)).append("'");
            }
            xmlArray.append(" />");
        }
        xmlArray.append("</results>");
        return xmlArray.toString();
    }

 

posted @ 2019-01-22 09:39  yshy  阅读(503)  评论(0编辑  收藏  举报