首页 > 解决方案 > 将从文件读取的字符串转换为 JSONObject android

问题描述

我创建了一个 JSONObject 并将值放入其中,如下所示。然后我将我的对象“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);

在文件中,我看到如下格式的文本。

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

我的问题是如何读取该特定文件并将这些文本转换回 JSONObject ?

标签: javaandroid

解决方案


要读取文件,您有 2 个选项:

使用 a 阅读,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
}

选项 2 是使用一个库,例如Okio

在您的 Gradle 文件中添加库

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

然后在您的活动中:

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

推荐阅读