programing

JSONObject 요소 업데이트

easyjava 2023. 3. 15. 20:01
반응형

JSONObject 요소 업데이트

JSONObject를 줬다고 칩시다.

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

JSONObject의 일부 값을 업데이트하려면 어떻게 해야 합니까?

다음과 같습니다.

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

put 메서드를 사용합니다.https://developer.android.com/reference/org/json/JSONObject.html

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

키를 삭제한 후 다음과 같이 변경된 키와 값의 쌍을 다시 추가합니다.

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

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

나는 너의 예를 사용하지 않았지만, 개념적으로는 똑같다.

안녕하세요 범용 방법을 제안할 수 있습니다.재귀를 이용하다

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

그건 작동할 거야.질문이 있으시면 말씀하세요.준비됐어요.

임의의 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());
        }

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

Kotlin에서 값을 상세하게 업데이트하는 재귀적 방법

예:setJsonValue("obj1/obj2/keyToUpdate", "new value")

fun setJsonValue(path: String, value: Any?) {
    setJsonValueRec(
        path = path.split("/"),
        index = 0,
        obj = jsonObj,
        value = value
    )
}

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

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

언급URL : https://stackoverflow.com/questions/15159610/update-elements-in-a-jsonobject

반응형