我正在尝试打开一个 Json 文件,该文件位于 res 我的文件结构中的 raw 文件夹中
但我尝试过的每种方法都失败了,我只需要字符串,因为我Json Strings已经可以解析了。
这是我的Json读者
public class Parser extends Activity {
public String getStringFromJson(String path) {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(path)));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
它在行中失败:
br = new BufferedReader(new InputStreamReader(getAssets().open(path)));
这就是logcat所说的:
02-03 10:44:13.440 2374-2374/com.example.ealcazar.kolibry E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ealcazar.kolibry/com.example.ealcazar.kolibry.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法来阅读 a Json?尝试访问我的文件时应该使用什么路径RAW folder?
非常感谢。
替换这行代码
br = new BufferedReader(new InputStreamReader(getAssets().open(path)));
Run Code Online (Sandbox Code Playgroud)
用这些
br = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.json));//Here json is the name of the file which is placed inside the RAW folder in yours resource
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6671 次 |
| 最近记录: |