繁体   English   中英

如何从Assests文件夹而不是Volley中的URL读取JSON文件

[英]How to read a JSON file from Assests folder instead of URL in Volley

我在assets文件夹中有一个JSON文件。 我想读取此文件并对数据进行处理。 我该如何使用Volley? 我找不到这样的东西。 我不想使用更多的库,例如gson或jackson。

我可以只用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;
}

为了能够使用它,您必须导入包“ org.json;”。

希望能帮助到你 !

Volley本身无法解析JSON,因此您需要使用GSON或...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM