读取本地Json文件必须要一次性全部读取,不能一行一行读取否则会出现各种你不理解的坑且读取的数据并不是你想要的数据,方法如下
InputStream is = null; ByteArrayOutputStream bos = null; try { is = context.getAssets().open("homepage.json"); bos = new ByteArrayOutputStream(); byte[] bytes = new byte[is.available()]; int len = 0; while ((len = is.read(bytes)) != -1) { bos.write(bytes, 0, len); LogUtil.d(TAG, "---- " + bytes.toString()); } final String json = new String(bos.toByteArray()); HomePageBean homePageBean = new Gson().fromJson(json, HomePageBean.class); LogUtil.d(TAG, "title" + homePageBean.getName()); } 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); } }