【问题标题】:Load External JSON file in Java Android在 Java Android 中加载外部 JSON 文件
【发布时间】: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...?

标签: java android json sqlite


【解决方案1】:

将您的 JSON 文件放入 assets 文件夹并从那里访问它。 您可以使用以下方法将数据读取为-

public static String getJSONData(Context context, String textFileName) {
    String strJSON;
    StringBuilder buf = new StringBuilder();
    InputStream json;
    try {
        json = context.getAssets().open(textFileName);

        BufferedReader in = new BufferedReader(new InputStreamReader(json, "UTF-8"));

        while ((strJSON = in.readLine()) != null) {
            buf.append(strJSON);
        }
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return buf.toString();
}

方法将返回 JSON 字符串,您可以创建 JSONObject 的实例

外部 json 文件为:sample.json

String jsonString = getJSONData(MainActivity.this, "sample.json");

JSONObject jsonObject = new JSONObject(jsonString);

【讨论】:

  • 你是个英雄。我尝试了很多东西,效果很好,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多