5

My json file contains,

{
  "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"
    }
  ]
}

I need to put another jsonobject into array, Out put should be like,

{
  "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"
    }
  ]
}

I used following code segment perform my requirement.

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 functions are,

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

but the output I am getting is,

{
  "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"
}

Please help me to get required format of json as output. Thanks in advance

1
  • You should read the file, parse it and then append the required changes. After that stringify the object and overwrite the existing file. You cant simply append in JSON file Commented Nov 22, 2017 at 6:14

6 Answers 6

3

Hope this would do what you want, Replace your

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

with this,

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I see what you did there! This is interesting
2

You are almost on the right track. you just have to add the JSONObject inside your JSONArray. Try this

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

Comments

0

You can use FileWriter to write in text files. Use below code:

try{ 

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

   fileWriter.write("Hello");

   fileWrite.close(); 

}catch(IOException e){ 

}

know more about it visit here

You can use Gson to convert object in string or vice-versa.

Comments

0

You will have to add the JSONObject inside your JSONArray appointments, try this

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

Comments

0

You need to get all the json objects from the json file first, parse it, then add new json array to it, finally save it back to the file.

Comments

-1

This is the method that appends new string to existing Json File and make it in proper format.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.