How to remove JSONArray element using Java How to remove JSONArray element using Java json json

How to remove JSONArray element using Java


What you have there is an array of objects. Therefore you'll have to loop through the array and remove the necessary data from each object, e.g.

for (int i = 0, len = jsonArr.length(); i < len; i++) {    JSONObject obj = jsonArr.getJSONObject(i);    // Do your removals    obj.remove("id");    // etc.}

I've assumed you're using org.json.JSONObject and org.json.JSONArray here, but the principal remains the same whatever JSON processing library you're using.

If you wanted to convert something like [{"id":215},{"id":216}] to [215,216] you could so something like:

JSONArray intArr = new JSONArray();for (int i = 0, len = objArr.length(); i < len; i++) {    intArr.put(objArr.getJSONObject(i).getInt("id"));}


This is useful sometimes in android when you want to use the json structure directly.

Notice that I only use this when I'm handling JSONObject inside the array.

public static JSONArray remove(final int idx, final JSONArray from) {    final List<JSONObject> objs = asList(from);    objs.remove(idx);    final JSONArray ja = new JSONArray();    for (final JSONObject obj : objs) {        ja.put(obj);    }    return ja;}public static List<JSONObject> asList(final JSONArray ja) {    final int len = ja.length();    final ArrayList<JSONObject> result = new ArrayList<JSONObject>(len);    for (int i = 0; i < len; i++) {        final JSONObject obj = ja.optJSONObject(i);        if (obj != null) {            result.add(obj);        }    }    return result;}


The following method will find the object in an array with the matching id, then return the filtered array.

public JSONArray removeObject(JSONArray array, String id) throws JSONException {    for (int i = 0; i < array.length(); i++) {        JSONObject obj = array.getJSONObject(i);        if (obj.getString("ID").equals(id)) {            array.remove(i);            //  Toast.makeText(this, "ENCONTRADO", Toast.LENGTH_SHORT).show();        }    }    return array;}