我的 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 的值更新为 app_001 为 appointmentId
我的功能是,
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();
}
我需要在我的代码中做哪些修改?请帮忙,提前谢谢。
Best Answer-推荐答案 strong>
在这里,您只需要遍历数组并更新数据:
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
关于android - 如何更新 JSON 文件数组中的特定对象?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/47513391/
|