如何在Android中将Json对象追加到现有的Json文件中

5
我的 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"
    }
  ]
}

我需要将另一个jsonobject放入数组中,输出应该是这样的:
{
  "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"
    },
    {
      "appointmentId": "app_003",
      "appointmentTitle": "AppointmentTitle3",
      "appointmentDate": "2017-11-26",
      "appointmentTime": "09:00",
      "appointmentStatus": "done",
      "appointmentType": "exam",
      "reminder": {
        "type": "alarm",
        "time": "08:45",
        "status": "on"
      },
      "appointmentDescription": "blablablablabla3"
    }
  ]
}

我使用以下代码段来实现我的需求。
File fileJson = new File(getApplicationContext().getExternalFilesDir("/app"), "app.json");

String strFileJson = getStringFromFile(fileJson.toString());

JSONObject jsonObj = new JSONObject(strFileJson);

jsonObj.put("appointmentId", "app_002");
jsonObj.put("appointmentTitle", "Appointment Title2");
jsonObj.put("appointmentDate", "2017-11-21");
jsonObj.put("appointmentTime", "01:30");
jsonObj.put("appointmentStatus", "active");
jsonObj.put("appointmentType", "meeting");

JSONObject reminder = new JSONObject();
reminder.put("type", "note");
reminder.put("time", "12:30");
reminder.put("status", "off");
jsonObj.put("reminder", reminder);
jsonObj.put("appointmentDescription", "blablablablabla2");

writeJsonFile(fileJson, jsonObj.toString()); 

"writeJsonFile"、"getStringFromFile"、"convertStreamToString"函数是什么。
public static String getStringFromFile(String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    fin.close();
    return ret;
}

public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    return sb.toString();
}

public static void writeJsonFile(File file, String json) {
    BufferedWriter bufferedWriter = null;
    try {

        if (!file.exists()) {
            Log.e("App","file not exist");
            file.createNewFile();
        }

        FileWriter fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(json);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

但是我得到的输出是,
{
  "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"
    }
  ],
  "appointmentId": "app_002",
  "appointmentTitle": "Appointment Title2",
  "appointmentDate": "2017-11-21",
  "appointmentTime": "01:30",
  "appointmentStatus": "active",
  "appointmentType": "meeting",
  "reminder": {
    "type": "note",
    "time": "12:30",
    "status": "off"
  },
  "appointmentDescription": "blablablablabla2"
}

请帮我输出所需的JSON格式。先行谢过。

你应该读取文件,解析它,然后追加所需的更改。之后将对象转换为字符串并覆盖现有文件。你不能简单地在JSON文件中追加。 - Manish Waran
6个回答

3
希望这可以达到你想要的效果,替换你的内容。
JSONObject jsonObj = new JSONObject(strFileJson);

jsonObj.put("appointmentId", "app_002");
jsonObj.put("appointmentTitle", "Appointment Title2");
jsonObj.put("appointmentDate", "2017-11-21");
jsonObj.put("appointmentTime", "01:30");
jsonObj.put("appointmentStatus", "active");
jsonObj.put("appointmentType", "meeting");

JSONObject reminder = new JSONObject();
reminder.put("type", "note");
reminder.put("time", "12:30");
reminder.put("status", "off");
jsonObj.put("reminder", reminder);
jsonObj.put("appointmentDescription", "blablablablabla2");

有了这个,

JSONObject PreviousJsonObj = new JSONObject(strFileJson);
JSONArray array = PreviousJsonObj.getJSONArray("appointments");
JSONObject jsonObj= new JSONObject();

jsonObj.put("appointmentId", "app_002");
jsonObj.put("appointmentTitle", "Appointment Title2");
jsonObj.put("appointmentDate", "2017-11-21");
jsonObj.put("appointmentTime", "01:30");
jsonObj.put("appointmentStatus", "active");
jsonObj.put("appointmentType", "meeting");

JSONObject reminder = new JSONObject();
reminder.put("type", "note");
reminder.put("time", "12:30");
reminder.put("status", "off");
jsonObj.put("reminder", reminder);
jsonObj.put("appointmentDescription", "blablablablabla2");
array.put(jsonObj);

JSONObject currentJsonObject = new JSONObject();
currentJsonObject.put("appointments",array);

我看到了你做的事情!这很有趣。 - Bamidele Clement Oke

2

你差不多走上了正确的道路。你只需要将JSONObject添加到JSONArray中即可。试试这个:

    JSONObject OldJsonObj = new JSONObject(strFileJson);
    JSONArray array = OldJsonObj.getJSONArray("appointments");
    JSONObject jsonObj= new JSONObject();


jsonObj.put("appointmentId", "app_002");
jsonObj.put("appointmentTitle", "Appointment Title2");
jsonObj.put("appointmentDate", "2017-11-21");
jsonObj.put("appointmentTime", "01:30");
jsonObj.put("appointmentStatus", "active");
jsonObj.put("appointmentType", "meeting");

JSONObject reminder = new JSONObject();
reminder.put("type", "note");
reminder.put("time", "12:30");
reminder.put("status", "off");
jsonObj.put("reminder", reminder);
jsonObj.put("appointmentDescription", "blablablablabla2");
array.put(jsonObj);  // put the data in array

JSONObject newJsonObject = new JSONObject(array.toString());

writeJsonFile(fileJson, newJsonObject .toString()); 

0

您可以使用FileWriter来写入文本文件。以下是代码:

try{ 

   FileWriter fileWriter = new FileWriter(Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.StampWallet/" + "SBLog.txt", true); 

   fileWriter.write("Hello");

   fileWrite.close(); 

}catch(IOException e){ 

}

想了解更多,请访问这里

您可以使用Gson将对象转换为字符串或反之亦然。


0

你需要将 JSONObject 添加到你的 JSONArray appointments 中,试试这个:

    JSONObject jsonObject=new JSONObject(strFileJson);
    JSONObject jsonObj=new JSONObject();
    JSONObject jObj=new JSONObject();


    try {
        jsonObj.put("appointmentId", "app_002");
        jsonObj.put("appointmentTitle", "Appointment Title2");
        jsonObj.put("appointmentDate", "2017-11-21");
        jsonObj.put("appointmentTime", "01:30");
        jsonObj.put("appointmentStatus", "active");
        jsonObj.put("appointmentType", "meeting");
        jObj.put("type", "note");
        jObj.put("time", "12:30");
        jObj.put("status", "off");
        jsonObj.put("reminder",jObj);
        JSONArray jsonArray=jsonObject.getJSONArray("appointments");
        jsonArray.put(jsonObj);
    } catch (JSONException e) {
        e.printStackTrace();
    }

0

首先需要从json文件中获取所有的json对象,进行解析,然后添加新的json数组,最后将其保存回文件。


-1

这是一种将新字符串附加到现有Json文件并使其格式正确的方法。

    public void runCheck() throws Exception {
    String fileName= "E:\\stores.json";     //my existing json file
    
    //this methods first gets the existing json string from our file.
                BufferedReader br = new BufferedReader(new FileReader(fileName));
                  StringBuilder sb = new StringBuilder();
                   line = br.readLine();
                    while (line != null) {
                        sb.append(line);
                        sb.append("\n");
                        line = br.readLine();
                    }            
                    br.close();   
                
    
    
      String mk="suraj";   //variable to be inserted in my new json
    
    //this methods removes the trailing bracket so that i can append my new json
                    String str =sb.toString();
                    String sourceWord="}";
                    StringBuilder strb=new StringBuilder(str);    
                    int index=strb.lastIndexOf(sourceWord);    
                    strb.replace(index,sourceWord.length()+index,"");    
                    System.out.println(strb.toString());
                    FileWriter fws = new FileWriter(fileName,false);
                    fws.write(strb.toString());//appends the string to the file
                    fws.close();
                    
    
    //now the method to insert new json
                    FileWriter fw = new FileWriter(fileName,true); //the true will append the new data
                    String json = "  , \n"
                            + "\""
                            + mk
                            + "\": \n"
                            + "{ \n"
                            +  "  \"prod\": \n"
                            +  "{ \n"
                               + "      \"MAGENTO_ADMIN_PASSWORD\": \""
                               + mk
                               + "\", \n"                  
                               + "      \"MAGENTO_ADMIN_USERNAME\" : \""
                               + mk
                               + "\", \n" 
                               + "      \"MAGENTO_BACKEND_NAME\" : \""
                               + mk
                               + "\", \n" 
                               + "      \"MAGENTO_BASE_URL\" : \""
                               + mk
                               + "\" \n"
                               + "    }, \n"
                               + "   \"uat\": \n"
                               + "    { \n" 
                               + "      \"MAGENTO_ADMIN_PASSWORD\": \""
                               + mk
                               + "\", \n"          
                               + "      \"MAGENTO_ADMIN_USERNAME\" : \""
                               + mk
                               + "\", \n" 
                               + "      \"MAGENTO_BACKEND_NAME\" : \""
                               + mk
                               + "\", \n" 
                               + "      \"MAGENTO_BASE_URL\" : \""
                               +mk
                               + "\" \n"
                               + "    }, \n" 
                               + "   \"stag\": \n"
                               + "    { \n" 
                               + "      \"MAGENTO_ADMIN_PASSWORD\": \""
                               + mk
                               + "\", \n"          
                               + "      \"MAGENTO_ADMIN_USERNAME\" : \""
                               + mk
                               + "\", \n" 
                               + "      \"MAGENTO_BACKEND_NAME\" : \""
                               + mk
                               + "\",\n" 
                               + "      \"MAGENTO_BASE_URL\" : \""
                               + mk
                               + "\" \n"
                               + "    } \n" 
                               + "} \n"; 
                        fw.write(json);//appends the string to the file
                        fw.write( "} \n");  //append my closing bracket, You can modify as per your convinience.
                    fw.close();                        
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接