如何从JSONArray中删除特定元素?

43

我正在开发一个应用程序,从服务器请求一个PHP文件。这个PHP文件返回一个JSONArray,其中包含JSONObjects作为其元素,例如:

[ 
  {
    "uniqid":"h5Wtd", 
    "name":"Test_1", 
    "address":"tst", 
    "email":"ru_tst@tst.cc", 
    "mobile":"12345",
    "city":"ind"
  },
  {...},
  {...},
  ...
]

我的代码:

/* jArrayFavFans is the JSONArray i build from string i get from response.
   its giving me correct JSONArray */
JSONArray jArrayFavFans=new JSONArray(serverRespons);
for (int j = 0; j < jArrayFavFans.length(); j++) {
  try {
    if (jArrayFavFans.getJSONObject(j).getString("uniqid").equals(id_fav_remov)) {
      //jArrayFavFans.getJSONObject(j).remove(j); //$ I try this to remove element at the current index... But remove doesn't work here ???? $
      //int index=jArrayFavFans.getInt(j);
      Toast.makeText(getParent(), "Object to remove...!" + id_fav_remov, Toast.LENGTH_SHORT).show();
    }
  } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}

我该如何从这个JSONArray中删除特定元素?
11个回答

0
删除多个职位
    public static void main(String[] args) throws JSONException {
        JSONArray array = new JSONArray();
        array.put(0, "0");
        array.put(1, "1");
        array.put(2, "2");
        array.put(3, "3");
        List<Integer> toRemove = new ArrayList<>();
        toRemove.add(1);
        toRemove.add(0);
        toRemove = toRemove.stream().sorted().collect(Collectors.toList());
        int removedCount = 0; // Once we remove the element from array, we should reduce the position also with the removed item size
        for (int position : toRemove) {
            int newPosition = position - removedCount;
            array.remove(newPosition);
            removedCount = removedCount + 1;
            
        }
        System.out.println(array.toString());// ["2","3"]
    }

我看到这是你的第一个回答,真棒。但是既然已经有一个被接受的答案了,新的回答应该试着改进它,或者至少更新过时的信息。那么,你为什么认为你的解决方案比已经被接受的答案更好呢? - Diego Borba
根据目前的写法,你的回答不够清晰。请编辑以添加更多细节,帮助其他人理解这如何回答所提出的问题。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接