如何在java中将数据库结果集转换为JSON格式?

时间:2016-01-18 13:44:12

标签: java json api jdbc automation

我想将db中的结果集转换为json格式,问题是当结果集作为多个行返回同一个id并带有一些重复数据时。

数据库示例:

===========================================================
USER_ID         NAME          PHONE_NUMBER         CITY
===========================================================
1               JACK          079999999999        New York
1               JACK          078888888888        Las Vegas

我想让我的json身体看起来像:

{ "USER_ID": 1,"NAME": JACK,"PHONE_NUMBER":[ 079999999999, 078888888888 ], "CITY": [ New York, Las Vegas ]}

这是我的代码:

                Statement stmt = con.createStatement();
                // Execute the SQL Query. Store results in ResultSet
                ResultSet rs = stmt.executeQuery(Query);
                System.err.println("Executing the query please wait ...");
                ResultSetMetaData rsmd=null;
                rsmd=(ResultSetMetaData) rs.getMetaData();
                int columnsCount=rsmd.getColumnCount();


                for (int j = 1; j <= columnsCount; j++) {
                    System.err.print(rsmd.getColumnName(j) + " || ");
                }


            JSONArray jsonArray = new JSONArray();
            while (rs.next()) {
                int total_rows = rs.getMetaData().getColumnCount();
                JSONObject obj = new JSONObject();

                for (int i = 0; i < total_rows; i++) {
                    String columnName = rs.getMetaData().getColumnLabel(i + 1).toLowerCase();
                    Object columnValue = rs.getObject(i + 1);

                    // if value in DB is null, then we set it to default value
                    if (columnValue == null){
                        columnValue = "null";
                    }

                    if (obj.has(columnName)){
                        columnName += "1";
                    }
                    obj.put(columnName, columnValue);

                }
                jsonArray.put(obj);

                System.out.print("\n");
                System.out.print("\n");

                String gsonBody = gson.toJson(jsonArray);

                System.err.println(gsonBody);
            }
            return jsonArray;

如何针对具有不同结果集的所有可能方案进行此更通用。

1 个答案:

答案 0 :(得分:0)

你正在使用哪种RDBMS?如果Postgres / db2是你的数据库,你可以直接将结果集作为JSON返回。