开发者

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

开发者 https://www.devze.com 2023-01-14 15:08 出处:网络
I started building an Android app that uses a flat file for storage.The app doesn\'t store more than six records, and I\'m familiar with JSON, so I just write out a JSONArray to the file.

I started building an Android app that uses a flat file for storage. The app doesn't store more than six records, and I'm familiar with JSON, so I just write out a JSONArray to the file.

I just discovered today, though, that the Android JSON API doesn't include a remove() option. Huh? Do I have to dump the array into another collection, remove it, then rebuild the J开发者_运维百科SONArray? What's the point?


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


You might want to check it out now. Seems like API 19 from Android (4.4) actually allows this method.

Call requires API level 19 (current min is 16): org.json.JSONArray#remove

I got that error while trying to use it. Hope it helps you, now that it's there!

0

精彩评论

暂无评论...
验证码 换一张
取 消