android 6.0 上传json android json文件_List

android 6.0 上传json android json文件_json_02

 

怎样解析data.json文件并且保存为Config对象?

第一步:使用数据流转换成字符串

private String loadConfig() {
    InputStream is = null;
    ByteArrayOutputStream bos = null;
    try {
        is = getAssets().open("data.json");
        bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = is.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        return bos.toString("utf-8");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bos != null)
                bos.close();
            if (is != null)
                is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
第二步:使用fastjson包
String json = loadConfig();
if (json != null) {
    List<Config> configs = JSON.parseArray(json, Config.class);
}

这里的configs集合就是json文件里的数据,注意json里的key是和实体类里的属性要保持一致;