Android 如何更新JSON文件数组中的特定对象?
我的json文件在内部存储器中的格式如下:Android 如何更新JSON文件数组中的特定对象?,android,json,Android,Json,我的json文件在内部存储器中的格式如下: { "appointments": [ { "appointmentId": "app_001", "appointmentTitle": "Appointment Title1", "appointmentDate": "2017-11-25", "appointmentTime": "10:30", "appointmentStatus": "active", "appointmentType": "meeting",
{
"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();
}
我需要在代码中做哪些修改?请提供帮助,提前感谢。这里是您的,您只需浏览阵列并更新数据:
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
JSONArray数组=json.getJSONArray(“约会”);
对于(int i=0;i
这样我才能理解你的问题;您想更改对象的标题还是对象的值?@Nero我提到了值