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

2022-09-01 01:56:37

我正在构建一个应用程序,其中我从服务器请求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 中删除特定元素?


答案 1

试试这个代码

ArrayList<String> list = new ArrayList<String>();     
JSONArray jsonArray = (JSONArray)jsonObject; 

if (jsonArray != null) { 
   int len = jsonArray.length();
   for (int i=0;i<len;i++){ 
    list.add(jsonArray.get(i).toString());
   } 
}
//Remove the element from arraylist
list.remove(position);
//Recreate JSON Array
JSONArray jsArray = new JSONArray(list);

编辑:使用将添加到键和值。所以,使用自己ArrayList"\"JSONArray

JSONArray list = new JSONArray();     
JSONArray jsonArray = new JSONArray(jsonstring); 
int len = jsonArray.length();
if (jsonArray != null) { 
   for (int i=0;i<len;i++)
   { 
       //Excluding the item at position
        if (i != position) 
        {
            list.put(jsonArray.get(i));
        }
   } 
}

答案 2

如果有人在 Android 平台上返回相同的问题,如果您的目标是 Android API-18 或更低版本,则无法使用内置方法。该方法在 API 级别 19 上添加。因此,最好的办法是扩展 为方法创建兼容的重写。remove()remove()JSONArrayremove()

public class MJSONArray extends JSONArray {

    @Override
    public Object remove(int index) {

        JSONArray output = new JSONArray();     
        int len = this.length(); 
        for (int i = 0; i < len; i++)   {
            if (i != index) {
                try {
                    output.put(this.get(i));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        } 
        return output;
        //return this; If you need the input array in case of a failed attempt to remove an item.
     }
}

编辑正如丹尼尔所指出的,默默地处理错误是不好的风格。代码得到改进。