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

发布时间 2023-08-29 14:20:55作者: 浪川宣哲
原始代码:
            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);