Android 讀取assets文件夾中json文件

這裏要介紹一下 讀取assets文件夾中json文件 轉換成list 集合json

只接看代碼 很是簡單spa

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了code

相關文章
相關標籤/搜索