0
点赞
收藏
分享

微信扫一扫

关于读取本地Json文件的坑

IT影子 2022-02-11 阅读 72
json

读取本地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);
    }
}
举报

相关推荐

0 条评论