Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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 JSONArray? What's the point?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...