0

I have created a JSONObject and put values in it like below . Then I converted my object "h" to string and write a file in the sdcard with that string.

JSONObject h = new JSONObject();
    try {
        h.put("NAme","Yasin Arefin");
        h.put("Profession","Student");
    } catch (JSONException e) {
        e.printStackTrace();
    }
String k =h.toString();

writeToFile(k);

In the file I see text written like the format below .

{"NAme":Yasin Arefin","Profession":"Student"}

My question is how do I read that particular file and convert those text back to JSONObject ?

Yamin
  • 15
  • 6
  • Possible duplicate of [How to convert jsonString to JSONObject in Java](https://stackoverflow.com/questions/5245840/how-to-convert-jsonstring-to-jsonobject-in-java) – MWB Jan 26 '19 at 08:19

1 Answers1

0

To read a file you have 2 options :

Read with a BufferReader and your code would look like this :

//Path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
//Load the file
File file = new File(sdcard,"file.json");
//Read text from file
StringBuilder text = new StringBuilder();
try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

The option 2 would be to use a library such as Okio:

In your Gradle file add the library

implementation 'com.squareup.okio:okio:2.2.0'

Then in your activity:

StringBuilder text = new StringBuilder();  
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
 for (String line; (line = source.readUtf8Line()) != null; ) {
  text.append(line);
  text.append('\n'); 
 }
}
113408
  • 3,364
  • 6
  • 27
  • 54
  • How do I convert it back to JSONObject ? JSONObject i = new JSONObject(text); is that okay ? – Yamin Jan 26 '19 at 08:30