我正在尝试使用JSONArray
从数据库中检索数据。我的代码运行良好,但它只显示数据库中的最后一项作为数据库中的项目数。
我的代码是:
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
JSONObject Obj = new JSONObject();
Connection conn = null;
try {
conn=prepareConnection();
} catch (ClassNotFoundException e1) {
System.out.println( "Error --> " + displayErrorForWeb(e1));
e1.printStackTrace();
} catch (SQLException e1) {
System.out.println( "Error --> " + displayErrorForWeb(e1));
e1.printStackTrace();
}
try {
JsonElement commentObj;
StringBuilder sb1=new StringBuilder(1024);
sb1.append("insert into ").append(uname.trim()).append("vcomments values(?,?,?,?)");
String sql1=sb1.toString();
PreparedStatement stmt1 = conn.prepareStatement(sql1);
stmt1.setString(1,uname);
stmt1.setString(2,message);
stmt1.setInt(3,itemId);
stmt1.setInt(4,albumId);
int i=stmt1.executeUpdate();
if(i!=1){
myObj.addProperty("success", false);
}
else {
myObj.addProperty("success", true);
}
PreparedStatement stmt = null;
String sql = null;
try {
StringBuilder sb=new StringBuilder(1024);
sb.append("select * from ").append(uname.trim()).append("vcomments").append(" where itemid=").append(itemId).append(" and albumid=").append(albumId);
sql=sb.toString();
stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
ArrayList<JSONObject> CommArray=new ArrayList<JSONObject>();
while(rs.next()){
Obj.put("uname",rs.getString("uname").trim());
Obj.put("comment",rs.getString("comments").trim());
CommArray.add(Obj);
}
JSONArray arrayObj=JSONArray.fromObject(CommArray);
commentObj=gson.toJsonTree(arrayObj);
myObj.add("commentInfo", commentObj);
out.println(myObj.toString());
rs.close();
stmt.close();
stmt = null;
conn.close();
conn = null;
}
catch(Exception e){System.out.println( "Error --> " + displayErrorForWeb(e));}
收到回复:
{"success":true,"commentInfo":[{"uname":"shyam","comment":"erxdg"},{"uname":"shyam","comment":"erxdg"},{"uname":"shyam","comment":"erxdg"},{"uname":"shyam","comment":"erxdg"}]}
数据库包含两个项目。最后一项是 erxdg 。 Servlet仅将响应发送回最后一项。
请有人帮我解决它.....谢谢............
答案 0 :(得分:1)
您必须为每个结果集创建一个新的JSONObject
。在循环中创建一个,并将其添加到数组中。否则,您只需替换旧对象的字段,并将其他引用添加到结果中。
while(rs.next()){
//new line:
JSONObject Obj = new JSONObject();
// original part looks fine:
Obj.put("uname",rs.getString("uname").trim());
Obj.put("comment",rs.getString("comments").trim());
CommArray.add(Obj);
}