[java] Update elements in a JSONObject

Lets say I gave a JSONObject

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

How do I update some of the values in the JSONObject?

Like below :

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

This question is related to java android json

The answer is


Generic way to update the any JSONObjet with new values.

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

Use the put method: https://developer.android.com/reference/org/json/JSONObject.html

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

Hello I can suggest you universal method. use recursion.

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

It should work. If you have questions, go ahead.. I'm ready.


Remove key and then add again the modified key, value pair as shown below :

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

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

I haven't used your example; but conceptually its same.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?