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

标签 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 的值,其中 app_001appointmentId

我的职责是,

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

关于android - 如何更新 JSON 文件数组中的特定对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47513391/

相关文章:

Android:AlertDialog 在 fragment 中看起来不同

javascript - 三个JS对象加载,给一个对象放一个颜色

javascript - ReactJS(初学者)使用 Youtube API - 返回的对象不允许我访问 VideoId 属性

javascript - Angularjs json数据读取

android - 以地理 Intent 开始的谷歌地图 7 将在最接近坐标的地址而不是确切位置放置图钉

android - 仅当该值在 sqlite 数据库中不存在时才插入,否则覆盖

java - 为什么我得到这个线性布局的空值

android - 使用 Android Gradle 插件 3.3.0 合并资源时构建失败

json - Play Framework : How to sort JSON alphabetically

json - 在 Scala 中读取 JsValue