如何从Assets文件夹中读取JSON文件而不是在Volley中读取URL

时间:2015-02-23 21:19:37

标签: java android json parsing android-volley

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

我可以用Volley来处理吗?

非常感谢。

2 个答案:

答案 0 :(得分:1)

你不需要凌空从资产目录中读取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;"

希望它有所帮助!

答案 1 :(得分:0)

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