简体   繁体   English

将从文件读取的字符串转换为JSONObject Android

[英]Convert string read from file to JSONObject android

I have created a JSONObject and put values in it like below . 我创建了一个JSONObject并将值放入其中,如下所示。 Then I converted my object "h" to string and write a file in the sdcard with that string. 然后,我将对象“ h”转换为字符串,并使用该字符串在sdcard中写入文件。

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 ? 我的问题是如何读取特定文件并将这些文本转换回JSONObject?

To read a file you have 2 options : 要读取文件,您有2个选择:

Read with a BufferReader and your code would look like this : 使用BufferReader读取,您的代码将如下所示:

//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 : 选项2是使用诸如Okio的库:

In your Gradle file add the library 在您的Gradle文件中添加库

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM