Why isn't there a remove(int position) method in Android's JSONArray?

This is useful sometimes in android when you want to use the json structure directly, without looping around to convert. Please use this only when you do things like removing a row on long clicks or something like that. Don't use that inside a loop!

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

I use:

public static JSONArray removeFrom(JSONArray jsonArray, int pos){
    JSONArray result = new JSONArray();
    try {
        for (int i = 0; i < jsonArray.length(); i++) {
            if (i != pos) {
                jsonArray.put(jsonArray.get(i));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

The point is that JSONArray and JSONObject are meant to (de)serialize data to JSON, not manipulate data. A remove() method may seem to make sense, but where's the limit? Would you expect to be able to access attributes on serialized objects? Access or update nested data structures?

The idea is, indeed, that you manipulate data structures "natively".

Tags:

Json

Android