从android资源加载JSON

时间:2017-09-27 17:58:15

标签: android json

我在资产中有JSON文件,我试图在我的MainActivity方法中读取它:

 private static List<JSONObject> getJSONArray(Context context) {
    JSONArray myJSONarr=new JSONArray();
    try
    {
        AssetManager am = context.getAssets();
        InputStream is = am.open("chineesecardsdata.json");
        String resultJson = is.toString();
        is.close();
        Log.d("mainActLog","file read ok: "+resultJson);

        try {
        }
        catch (JSONException e)
        {
        }
    }
    catch(
            IOException e)
    {
        Log.d("mainActLog","file read fail");
    }
}

在日志中我有:

  

文件读取正常:   android.content.res.AssetManager$AssetInputStream@b123fb4

1 个答案:

答案 0 :(得分:1)

    public String loadJSONFromAsset( Context context ) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("yourfilename.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
}

解析JSON

try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONArray array = new JSONArray(loadJSONFromAsset());

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }