【问题标题】:Android, How to read from a Json in the raw folderAndroid,如何从原始文件夹中的 Json 读取
【发布时间】:2016-02-03 09:47:53
【问题描述】:

我正在尝试打开一个 Json 文件,该文件位于 res 内的原始文件夹中 My file structure

但是我尝试过的每种方法都失败了,我只需要字符串,因为我已经可以解析 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();
    }
}

它在行中失败:

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

有没有更简单的方法来阅读Json?尝试访问RAW folder 中的文件时应该使用什么路径?

非常感谢。

【问题讨论】:

  • 我的问题是我将 res 文件夹与 assets 文件夹混淆了,而且我得到了错误的上下文。我在 Android Studio 中创建了一个资产文件夹,并通过将它声明为静态并在 onCreate (MainActivity.context.getResources) 中分配它来从我的 mainActivity 中获取上下文

标签: java android json


【解决方案1】:

替换这行代码

br = new BufferedReader(new InputStreamReader(getAssets().open(path)));

有了这些

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

【讨论】:

  • Parser.this.getResources() => getResources() ...你不需要Parser.this
  • 有时它会在那里抛出异常@Selvin .. 我使用 ClassName.getResoure() 而不是 getResource() 方法.. 感谢您的建议:)
  • 有时它会抛出异常 ...如果您知道 java 则根本不可能...这是异常吗?还是编译时错误? ...所以你像这样调用类中的每个方法? class C { void r() {} void t() {} void main() { C.this.r(); C.this.t();}}呵呵
  • 你怎么看.. 在访问资源之前使用 CLASSNAME.this 是不好的做法吗??
  • 感谢解答,但是问题没有解决,至少现在好像知道文件在哪里了,crash还在同一行,logcat现在是:02-03 11:05:38.740 12864-12864/com.example.ealcazar.kolibry E/AndroidRuntime: java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.example.ealcazar.kolibry/com.example.ealcazar.kolibry.MainActivity} :java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void java.io.BufferedReader.close()'
猜你喜欢
  • 2015-12-07
  • 2022-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多