如何更新JSON文件数组中的特定对象?

时间:2017-11-27 14:33:21

标签: android json

我在内部存储中的json文件的格式是,

{
"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"
}
]
}

我需要将appointmentTitle的{​​{1}}更新为app_001

我的功能是,

appointmentId

我的代码中需要做哪些修改?请提前帮助,谢谢。

1 个答案:

答案 0 :(得分:4)

在这里,您只需要浏览数组并更新数据:

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