【发布时间】:2015-05-25 18:50:59
【问题描述】:
我刚开始学习 Java。我目前正在开发一个从 .JSON 文件中检索数据并将其存储到 SQLite 数据库中的小型应用程序。
我正在尝试打开一个 .JSON 文件并将其存储为 JSONObject。这是我读取 JSON 文件的代码。
private JSONObject readFile(String path) {
StringBuilder sb = new StringBuilder();
try {
FileReader in = new FileReader(new File(path));
int b;
while((b = in.read()) != -1) {
sb.appendCodePoint(b);
}
in.close();
return new JSONObject(sb.toString());
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
我的 JSON 文件存储在:app\src\main\java\proj\bb\database\jsonFiles
我目前像这样调用 readFile 方法:,但它会抛出一个NullPointer。 (DatabaseOperations 是类名)。
JSONObject jsonFile = readFile(DatabaseOperations.class.getResource("filename.json").toString());
JSONArray arr = jsonFile.getJSONArray("someArray");
我也试过这个没有成功:
JSONObject jsonFile = readFile("jsonFiles/filename.json").toString());
JSONArray arr = jsonFile.getJSONArray("someArray");
所以我的问题是,我需要作为参数传递的路径是什么?还是我做错了什么?
提前致谢!
【问题讨论】:
-
JSONObject profile = new JSONObject(yourString); -
是的,但是
yourString...?