0

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.

Nickolay
  • 31,095
  • 13
  • 107
  • 185
dummyDroid
  • 37
  • 1
  • 1
  • 4

2 Answers2

1

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 !

Guillaume agis
  • 3,756
  • 1
  • 20
  • 24
0

Volley itself is not able to parse JSON, so you need to use GSON or ...

maxxxo
  • 672
  • 3
  • 10
  • 28