简体   繁体   English

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

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

I have a JSON file in the assets folder. 我在assets文件夹中有一个JSON文件。 I'd like to read this file and do something with the data. 我想读取此文件并对数据进行处理。 How can I use Volley for this? 我该如何使用Volley? I can't find anything like this. 我找不到这样的东西。 I don't want to use more libraries like gson or jackson. 我不想使用更多的库,例如gson或jackson。

Can I handle it with just Volley? 我可以只用Volley吗?

Thanks a Lot. 非常感谢。

You dont need volley to read a Json file from the asset directory. 您不需要排球即可从资产目录读取Json文件。

In my case, I load an array of Json from the file into my string "filePath". 就我而言,我将文件中的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();
    }

In my utils file : 在我的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;
}

To be able to use it your have to import the package "org.json;" 为了能够使用它,您必须导入包“ org.json;”。 .

Hope it helps ! 希望能帮助到你 !

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

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

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