美文网首页Android开发
Android开发本地json文件转为bean

Android开发本地json文件转为bean

作者: 你的益达233 | 来源:发表于2021-05-12 15:55 被阅读0次

一、json文件放在assets目录下

如下图:

json.png

二、关键的json文件转为String

public class JsonDataUtil {

    public static String getJson(Context context,String fileName){
        StringBuilder stringBuilder = new StringBuilder();

        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)
            ));
            String line;
            while ((line = bf.readLine()) != null){
                stringBuilder.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}

三、调用示例

String jsonStr = JsonDataUtil.getJson(this,"tblist.json");
    MsgTBListResult msgTBListResult = new Gson().fromJson(jsonStr,MsgTBListResult.class);

相关文章

网友评论

    本文标题:Android开发本地json文件转为bean

    本文链接:https://www.haomeiwen.com/subject/hamadltx.html