简体   繁体   中英

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

I have a JSON file in the assets folder. I'd like to read this file and do something with the data. How can I use Volley for this? I can't find anything like this. I don't want to use more libraries like gson or jackson.

Can I handle it with just Volley?

Thanks a Lot.

You dont need volley to read a Json file from the asset directory.

In my case, I load an array of Json from the file into my string "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 :

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;" .

Hope it helps !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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