java - 在 Android api lvl 19 之前删除 JsonObeject

标签 java android arrays json

你好,我有一个 json

String  prev_string= [
        {
            "mac_address": "D3-D3-D3-D3-D4",
            "minor": "2333",
            "time": "11-12-2014 2:36 PM",
            "major": "4444"
        },
        {
            "mac_address": "D3-D3-D3-D3-D3",
            "minor": "45555",
            "time": "11-12-2014 2:36 PM",
            "major": "2322"
        }
    ]
JSONArray json= new JSONArray(prev_string);
json.remove(1);

我需要删除第二个对象,json.remove(1) 工作正常,但在 lvl 19 之前的 android 中不起作用。remove,我该如何使其工作?

问候!

最佳答案

是的,令人惊讶的是它直到 API 19 才添加。您可以定义一个实用方法,在其中迭代源对象,并将所有元素添加到新对象(指定索引除外)。像这样的事情:

public static JSONArray removeJsonObjectAtJsonArrayIndex(JSONArray source, int index) throws JSONException {
    if (index < 0 || index > source.length() - 1) {
        throw new IndexOutOfBoundsException();
    }

    final JSONArray copy = new JSONArray();
    for (int i = 0, count = source.length(); i < count; i++) {
        if (i != index) copy.put(source.get(i));
    }
    return copy;
}

关于java - 在 Android api lvl 19 之前删除 JsonObeject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27427999/

相关文章:

android - 仅从画廊获取图像

c++ - 指向数组的指针

android - Expo Developer Tools 与 Expo CLI 断开连接

php数组组合

javascript - JS数组查找和替换?

java - 迁移两个 Realm 实例之一

java - 我可以在录制时为 WireMock 指定一个 --proxy-all 参数以匹配任何网站吗?

Mac OSX 上的 Java ProcessBuilder 看不到 Python 3

java - 两个变量之间空检查的替代写法?

android - Firebase 身份验证用户界面 : Is there an UI to let user edit their profile?