【问题标题】:How to read a JSON file from Assests folder instead of URL in Volley如何从 Assets 文件夹而不是 Volley 中的 URL 读取 JSON 文件
【发布时间】:2015-02-23 21:19:37
【问题描述】:

我在assets 文件夹中有一个 JSON 文件。我想阅读这个文件并对数据做一些事情。我该如何使用 Volley?我找不到这样的东西。我不想使用更多像 gson 或 jackson 这样的库。

我可以只用 Volley 来处理它吗?

非常感谢。

【问题讨论】:

    标签: java android json parsing android-volley


    【解决方案1】:

    您不需要 volley 从资产目录中读取 Json 文件。

    在我的例子中,我将文件中的 Json 数组加载到我的字符串“filePath”中。

    final String filePath = readFromAsset(act, "json_to_load.json"); //act is my current activity
        try {
            JSONArray obj = new JSONArray(filePath);
            for (int i = 0; i < obj.length(); i++) {
                JSONObject jo = obj.getJSONObject(i);
                // do stuff
    
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

    在我的 utils 文件中:

    private static String readFromAsset(Activity act, String fileName)
    {
        String text = "";
        try {
            InputStream is = act.getAssets().open(fileName);
    
            int size = is.available();
    
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            text = new String(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;
    }
    

    要使用它,您必须import the package "org.json;"

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      Volley 本身无法解析 JSON,所以需要使用 GSON 或 ...

      【讨论】:

        猜你喜欢
        • 2013-06-09
        • 1970-01-01
        • 2014-01-26
        • 1970-01-01
        • 2018-02-20
        • 2020-10-16
        • 2018-02-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多