ResultSet到java servlet中的Json

时间:2015-06-28 15:19:16

标签: java json servlets

尝试从数据库获取数据并存储在JSON对象中,如下所示:

try {
            JsonObject jsonResponse = new JsonObject();
            JsonArray data = new JsonArray();
            JsonArray row = new JsonArray();
            PrintWriter out = response.getWriter();

            Connection con = OracleDBConnection.getConnection();
            String query = "Select * from CUSTOMER_DEMOGRAPHICS";
            Statement st = con.createStatement();
            ResultSet rSet = st.executeQuery(query);

            while (rSet.next()) 
            {
                row.add(new JsonPrimitive(rSet.getString("COUNTRY")));
                row.add(new JsonPrimitive(rSet.getString("STATE")));
                row.add(new JsonPrimitive(rSet.getString("CITY")));
                data.add(row);
            }

            jsonResponse.add("ResponseData", data);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            out.print(jsonResponse);
            out.flush();
            System.out.println(jsonResponse);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

数据库中的表结构:

COUNTRY     STATE       CITY
================================
AUSTRALIA   VICTORIA    MELBOURNE
AUSTRALIA   NEW SOUTH   SYDNEY

问题是当我打印json时,它会按如下方式为每行打印两次而不是一次。

{ "ResponseData": [["AUSTRALIA","VICTORIA","MELBOURNE","AUSTRALIA ","NEW SOUTH WALES","SYDNEY"], ["AUSTRALIA","VICTORIA","MELBOURNE","AUSTRALIA ","NEW SOUTH WALES","SYDNEY"]] }

2 个答案:

答案 0 :(得分:2)

您正在创建一行,并将其两次添加到数组中。这条线

JsonArray row = new JsonArray();

应该内部循环。不在外面。

答案 1 :(得分:0)

我认为您应该将此代码添加到while()

的开头
row = new JsonArray();