更新JSONObject中的元素

bxjv4tth  于 2022-12-30  发布在  其他
关注(0)|答案(6)|浏览(222)

假设我给了一个JSONObject

{
 "person":{"name":"Sam", "surname":"ngonma"},
 "car":{"make":"toyota", "model":"yaris"}
 }

如何更新JSONObject中的一些值?
如下所示:

String name = jsonArray.getJSONObject(0).getJSONObject("person").getString("name");
name = "Sammie";
t5zmwmid

t5zmwmid1#

使用put方法:https://developer.android.com/reference/org/json/JSONObject.html

JSONObject person =  jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");
whlutmcx

whlutmcx2#

删除键,然后再次添加修改后的键、值对,如下所示:

JSONObject js = new JSONObject();
    js.put("name", "rai");

    js.remove("name");
    js.put("name", "abc");

我没有用你的例子但概念上是相同的。

k4ymrczo

k4ymrczo3#

你好,我可以建议你通用的方法。使用递归。

public static JSONObject function(JSONObject obj, String keyMain,String valueMain, String newValue) throws Exception {
    // We need to know keys of Jsonobject
    JSONObject json = new JSONObject()
    Iterator iterator = obj.keys();
    String key = null;
    while (iterator.hasNext()) {
        key = (String) iterator.next();
        // if object is just string we change value in key
        if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
            if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
                // put new value
                obj.put(key, newValue);
                return obj;
            }
        }

        // if it's jsonobject
        if (obj.optJSONObject(key) != null) {
            function(obj.getJSONObject(key), keyMain, valueMain, newValue);
        }

        // if it's jsonarray
        if (obj.optJSONArray(key) != null) {
            JSONArray jArray = obj.getJSONArray(key);
            for (int i=0;i<jArray.length();i++) {
                    function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
            }
        }
    }
    return obj;
}

应该可以的如果你有问题尽管问我准备好了。

agxfikkp

agxfikkp4#

使用新值更新任何JSONObjet的通用方法。

private static void updateJsonValues(JsonObject jsonObj) {
    for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
        JsonElement element = entry.getValue();
        if (element.isJsonArray()) {
            parseJsonArray(element.getAsJsonArray());
        } else if (element.isJsonObject()) {
            updateJsonValues(element.getAsJsonObject());
        } else if (element.isJsonPrimitive()) {
            jsonObj.addProperty(entry.getKey(), "<provide new value>");
        }

    }
}

private static void parseJsonArray(JsonArray asJsonArray) {
    for (int index = 0; index < asJsonArray.size(); index++) {
        JsonElement element = asJsonArray.get(index);
        if (element.isJsonArray()) {
            parseJsonArray(element.getAsJsonArray());
        } else if (element.isJsonObject()) {
            updateJsonValues(element.getAsJsonObject());
        }

    }
}
wfauudbj

wfauudbj5#

public static JSONObject updateJson(JSONObject obj, String keyString, String newValue) throws Exception {
            JSONObject json = new JSONObject();
            // get the keys of json object
            Iterator iterator = obj.keys();
            String key = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                // if the key is a string, then update the value
                if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
                    if ((key.equals(keyString))) {
                        // put new value
                        obj.put(key, newValue);
                        return obj;
                    }
                }

                // if it's jsonobject
                if (obj.optJSONObject(key) != null) {
                    updateJson(obj.getJSONObject(key), keyString, newValue);
                }

                // if it's jsonarray
                if (obj.optJSONArray(key) != null) {
                    JSONArray jArray = obj.getJSONArray(key);
                    for (int i = 0; i < jArray.length(); i++) {
                        updateJson(jArray.getJSONObject(i), keyString, newValue);
                    }
                }
            }
            return obj;
        }
gajydyqb

gajydyqb6#

Kotlin中更新深度值的递归方法
示例:setString("obj1/obj2/keyToUpdate", "new value")

fun setString(path: String, value: String) {
    setStringRec(
        path = path.split("/"),
        index = 0,
        obj = jsonObj,
        value = value
    )
}

private fun setStringRec(path: List<String>, index: Int, obj: JSONObject, value: String): JSONObject {
    return obj.put(
        path[index],
        when (index) {
            path.lastIndex -> value

            else -> setStringRec(
                path = path,
                index = index + 1,
                obj = obj.getJSONObject(path[index]),
                value = value
            )
        }
    )
}

相关问题