Gson读取json字符串中结果需要转泛型的情况解决方案

原始代码:
            Gson gson = new Gson();
            ArrayList<Fld> fixed = gson.fromJson(new FileReader(headFilePath), ArrayList.class);
            for (Fld fld : fixed) {
                int fld_len = fld.getFld_len();
            }

错误显示:com.google.gson.internal.LinkedTreeMap cannot be cast to cn.com.a.b.c

解决方案:
使用$Gson$Types.newParameterizedTypeWithOwner先生成Type,后使用
解决方案代码
Gson gson = new Gson();
Type type = $Gson$Types.newParameterizedTypeWithOwner(null, ArrayList.class, Fld.class);
ArrayList<Fld> fixed = gson.fromJson(new FileReader(headFilePath), type);

 

posted @ 2023-08-29 14:14  浪川宣哲  阅读(28)  评论(0)    收藏  举报