Android JSON in Android with org.json Updating the elements in the JSON

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

sample json to update

 {
 "student":{"name":"Rahul", "lastname":"sharma"},
 "marks":{"maths":"88"}
 }

To update the elements value in the json we need to assign the value and update.

try {
    // Create a new instance of a JSONObject
    final JSONObject object = new JSONObject(jsonString);
    
    JSONObject studentJSON = object.getJSONObject("student");
    studentJSON.put("name","Kumar");
  
     object.remove("student");

     object.put("student",studentJSON);

    // Calling toString() on the JSONObject returns the JSON in string format.
    final String json = object.toString();
    
} catch (JSONException e) {
    Log.e(TAG, "Failed to create JSONObject", e);
}

updated value

 {
 "student":{"name":"Kumar", "lastname":"sharma"},
 "marks":{"maths":"88"}
 }


Got any Android Question?