Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

android

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.

like image 593
Kavin-K Avatar asked Nov 20 '25 04:11

Kavin-K


1 Answers

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
like image 195
diegoveloper Avatar answered Nov 22 '25 17:11

diegoveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!