0

每当我将第二个 JSONObject 添加到 JSONArray 时,它都会覆盖先前的数组对象值。我的 java servlet 代码是-

  JsonArray ja=new JsonArray();
  JsonObject j;  
  j = new JsonObject();

  j.add("uid", j);
  j.add("fname", j);
  j.add("lname", j);

  for(int i=0;i<uid_list.size();i++){
      out.println(uid_list.get(i).toString());
      out.println(fname_list.get(i).toString());                  
      out.println(lname_list.get(i).toString());
      j.addProperty("uid", uid_list.get(i).toString());
      j.addProperty("fname", fname_list.get(i).toString());
      j.addProperty("lname", lname_list.get(i).toString());
      ja.add(j);
      out.println(ja.toString());

  }

  out.println(ja.toString());

输出是:

abc bcd cde [{"uid":"abc","fname":"bcd","lname":"cde"}] xyz wxy uyw [{"uid":"xyz","fname":"wxy","lname":"uyw"},{"uid":"xyz","fname":"wxy","lname":"uyw"}] [{"uid":"xyz","fname":"wxy","lname":"uyw"},{"uid":"xyz","fname":"wxy","lname":"uyw"}]

有人可以给我解决方案吗

4

1 回答 1

3

您正在循环中修改 JsonObject 的同一实例。在循环中创建新的 JsonObject,

for(int i=0;i<uid_list.size();i++){
  j=new JsonObject();
  out.println(uid_list.get(i).toString());
于 2013-03-29T19:32:35.153 回答