Update elements in a JSONObject

JavaAndroidJson

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

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

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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

    }
}

Solution 5 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarryView Question on Stackoverflow
Solution 1 - JavacowlsView Answer on Stackoverflow
Solution 2 - Javarai.skumarView Answer on Stackoverflow
Solution 3 - JavaeabyshevView Answer on Stackoverflow
Solution 4 - JavaManohar ThummanapellyView Answer on Stackoverflow
Solution 5 - Javashafi kkView Answer on Stackoverflow