Android 读取assets文件夹中json文件

这里要介绍一下 读取assets文件夹中json文件 转换成list 集合

只接看代码 非常简单

public static List<State> getStates(Context context) {
        InputStream is = null;
        ByteArrayOutputStream bos = null;
        try {
            is = context.getAssets().open("area.json");
            bos = new ByteArrayOutputStream();
            byte[] bytes = new byte[4 * 1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            final String json = new String(bos.toByteArray());
            final Areas areas = JSON.parseObject(json, Areas.class);
            final List<State> states = areas.getStates();

            return states;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                if (bos != null)
                    bos.close();
            } catch (IOException e) {
                Log.e(TAG, "getStates", e);
            }
        }
        return null;
    }

对应json 写好实体类 就OK了

posted @ 2017-05-31 10:34  TeddyYan  阅读(5440)  评论(0编辑  收藏  举报