Kavin-K
Kavin-K

Reputation: 2117

How to update a specific object inside an array of a JSON file?

format of my json file in internal storage is like,

{
"appointments": [
{
  "appointmentId": "app_001",
  "appointmentTitle": "Appointment Title1",
  "appointmentDate": "2017-11-25",
  "appointmentTime": "10:30",
  "appointmentStatus": "active",
  "appointmentType": "meeting",
  "reminder": {
    "type": "notification",
    "time": "10:15",
    "status": "off"
  },
  "appointmentDescription": "blablablablabla1"
},
{
  "appointmentId": "app_002",
  "appointmentTitle": "AppointmentTitle2",
  "appointmentDate": "2017-11-26",
  "appointmentTime": "09:00",
  "appointmentStatus": "done",
  "appointmentType": "exam",
  "reminder": {
    "type": "alarm",
    "time": "08:45",
    "status": "on"
  },
  "appointmentDescription": "blablablablabla2"
}
]
}

I need to update value of appointmentTitle which has app_001 as appointmentId

my function is,

String configFileString = "";

            File configFile = new File(getApplicationContext().getExternalFilesDir("/appointments"), "appointments.json");
            try {
                configFileString = getStringFromFile(configFile.toString());
                JSONObject json = new JSONObject(configFileString);
                JSONArray array = json.getJSONArray("appointments");

            } catch (Exception e) {
                e.printStackTrace();
            }

What should be the modifications that I need to do in my code? please help, thanks in advance.

Upvotes: 3

Views: 1897

Answers (1)

diegoveloper
diegoveloper

Reputation: 103431

Here you have , you just have to go through the array and update your data:

JSONArray array = json.getJSONArray("appointments");
for(int i=0;i < array.length(); i++){
    JSONObject object = array.getJSONObject(i);
    String id = object.getString("appointmentId");
    if (id.equals("app_001")){
       object.put("appointmentTitle","your value updated");
    }
}

String stringJSON = array.toString();
//save your data

Upvotes: 5

Related Questions