如何从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个回答

50

尝试使用这段代码

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
如果(jsonArray != null)在您的编辑示例中没有意义,因为它永远不会为null。即使它是null,它之前的行也会抛出NullPointerException。这也适用于原始示例。 - hounce

20

如果有人针对Android平台返回相同的问题,如果你的目标是Android API-18或更低版本,则无法使用内置的remove()方法。 remove()方法是在API级别19上添加的。因此,最好的做法是扩展JSONArray以创建兼容的覆盖remove()方法。

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.
     }
}

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


1
这是糟糕的编码风格。如果出现错误,元素不会被移除,但调用代码无法知道这一点。更好的方法是在函数头中使用 throws JSONException 而不是使用 try..catch。 - Daniel Alder
1
@DanielAlder,“remove”方法无法抛出异常,因为被重写的方法没有这样做。 - C--
1
好的,在这种情况下,我会放置一个 throw new RuntimeException(e)(或 InternalError)而不是 e.printStackTrace();return this; - 以防万一。 - Daniel Alder
不建议扩展默认类。最好在使用它的类中创建remove()方法。 - Stack Overflow

4
public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {

JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){     
    if(i!=pos)
        Njarray.put(jarray.get(i));     
}
}catch (Exception e){e.printStackTrace();}
return Njarray;

}

3
 JSONArray jArray = new JSONArray();

    jArray.remove(position); // For remove JSONArrayElement

注意:如果JSONArray中没有remove()方法,则...

Android API 19(4.4)实际上允许使用此方法。

调用需要API级别19(当前最小级别为16):org.json.JSONArray#remove

右键单击项目,选择“属性”。

从左侧选项中选择Android。

选择项目构建目标大于API 19。

希望对您有所帮助。


2

我猜你正在使用Me版本,建议在你的代码(JSONArray.java)中手动添加这个函数块:

public Object remove(int index) {
    Object o = this.opt(index);
    this.myArrayList.removeElementAt(index);
    return o;
}

在Java版本中,它们使用ArrayList,在ME版本中,它们使用Vector。


1
你可以使用反射技术。
一家中文网站提供了相关解决方案: http://blog.csdn.net/peihang1354092549/article/details/41957369
如果您不懂中文,请尝试使用翻译软件阅读。
他提供了旧版本的代码:
public void JSONArray_remove(int index, JSONArray JSONArrayObject) throws Exception{
    if(index < 0)
        return;
    Field valuesField=JSONArray.class.getDeclaredField("values");
    valuesField.setAccessible(true);
    List<Object> values=(List<Object>)valuesField.get(JSONArrayObject);
    if(index >= values.size())
        return;
    values.remove(index);
}

1
在我的情况下,我想要删除状态为非零值的json对象,所以我创建了一个名为“removeJsonObject”的函数,该函数接受旧的json并提供所需的json,并在构造函数中调用该函数。
public CommonAdapter(Context context, JSONObject json, String type) {
        this.context=context;
        this.json= removeJsonObject(json);
        this.type=type;
        Log.d("CA:", "type:"+type);

    }

public JSONObject removeJsonObject(JSONObject jo){
        JSONArray ja= null;
        JSONArray jsonArray= new JSONArray();
        JSONObject jsonObject1=new JSONObject();

        try {
            ja = jo.getJSONArray("data");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        for(int i=0; i<ja.length(); i++){
            try {

                if(Integer.parseInt(ja.getJSONObject(i).getString("status"))==0)
                {
                    jsonArray.put(ja.getJSONObject(i));
                    Log.d("jsonarray:", jsonArray.toString());
                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        try {
            jsonObject1.put("data",jsonArray);
            Log.d("jsonobject1:", jsonObject1.toString());

            return jsonObject1;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

0
We can use iterator to filter out the array entries instead of creating a new  Array. 

'public static void removeNullsFrom(JSONArray array) throws JSONException {
                if (array != null) {
                    Iterator<Object> iterator = array.iterator();
                    while (iterator.hasNext()) {
                        Object o = iterator.next();
                        if (o == null || o == JSONObject.NULL) {
                            iterator.remove();
                        }
                    }
                }
            }'

欢迎来到StackOverflow!请确保在您的答案中添加解释,以帮助他人理解。 - Markus
希望这能解决问题,但请附上代码解释,以便用户获得他/她真正想要的完美理解。 - Jaimil Patel

0
static JSONArray removeFromJsonArray(JSONArray jsonArray, int removeIndex){
    JSONArray _return = new JSONArray();
    for (int i = 0; i <jsonArray.length(); i++) {
        if (i != removeIndex){
            try {
                _return.put(jsonArray.getJSONObject(i));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    return _return;
}

0

如果要从Android的Listview中删除某些元素,则会删除您指定的元素并将其绑定到Listview。

BookinhHistory_adapter.this.productPojoList.remove(position);

BookinhHistory_adapter.this.notifyDataSetChanged();

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