尝试从数据库获取数据并存储在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"]]}
最佳答案
您正在创建单行,并将其添加到数组两次。线
JsonArray row = new JsonArray();
应该在循环内。不在外面