java - 将从文件读取的字符串转换为 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 ?
解决方案
要读取文件,您有 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');
}
}
推荐阅读
- asp.net-core - ASP.Net Core API 从 SSIS 给出 503 错误
- javascript - 无法找到仅用于测试的按钮组件
- symfony - Symfony 5 - 刷新用户会话而不重新登录
- c# - 从多个属性到复杂对象的 AutoMapper 映射失败,ReverseMap 和自定义值解析器
- python - 检查一个句子是否连续包含多个单词(Python)
- flutter - 在 iOS Flutter 应用中提供 Flutter WebApp
- css - 使用 css 自定义文本编辑器
- python - 为什么函数没有参数运行?
- javascript - 我想导入一个包含 200 个演讲的列表并通过单击按钮生成随机演讲,永远不会两次获得相同的演讲
- amazon-web-services - AWS Proton 参数 - 阐明如何在 CF 模板中使用 schema.yaml 参数