如何将Json对象附加到android中的现有json文件中

时间:2017-11-22 06:09:34

标签: 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"
    }
  ]
}

我需要将另一个jsonobject放入数组中,Out put应该是,

{
  "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()); 

writeJsonFilegetStringFromFileconvertStreamToString函数是

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格式作为输出。提前致谢

6 个答案:

答案 0 :(得分:1)

你几乎走在正确的轨道上。您只需在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()); 

答案 1 :(得分:1)

希望这可以做你想要的,替换你的

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);

答案 2 :(得分: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){ 

}

了解更多信息,请访问here

您可以使用Gson转换字符串中的对象,反之亦然。

答案 3 :(得分:0)

您必须在JSONArray appointments中添加JSONObject,试试这个

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

答案 4 :(得分:0)

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

答案 5 :(得分:-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();                        
        }