代码之家  ›  专栏  ›  技术社区  ›  Kavin-K

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

  •  3
  • Kavin-K  · 技术社区  · 9 年前

    我的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();
                }
    

    我需要在代码中做什么修改?请帮忙,提前谢谢。

    1 回复  |  直到 9 年前
        1
  •  4
  •   diegoveloper    9 年前

    在这里,您只需遍历数组并更新数据:

    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