当前位置: 首页> 汽车> 时评 > com.alibaba.fastjson.TypeReference的错误使用-----加泛型

com.alibaba.fastjson.TypeReference的错误使用-----加泛型

时间:2025/7/11 14:24:15来源:https://blog.csdn.net/qq_27724109/article/details/140847648 浏览次数: 1次

我是一个懒人,不想看见重复的代码,最近因为这个特点踩了一个坑

代码里少不了RestApiResponse例如下面的代码

@Data
public class RestApiResponse<T> {private Integer code;private String msg;private T data;private LocalDateTime timestamp = LocalDateTime.now();
}

最近突发奇想,想用下面这个方法把json数据反序列化的代码封装起来

    public static <T> RestApiResponse<T> of(String json) {return JSON.parseObject(json, new TypeReference<RestApiResponse<T>>() {});}

然后,就发现,T的类型识别不了了

@Data
public class ParseJson {Integer a;public static void main(String[] args) {String json = "{\"code\":0,\"msg\":\"success\",\"data\":{\"a\":1},\"timestamp\":\"2024-08-01 14:32:24\"}";RestApiResponse<ParseJson> obj1 = RestApiResponse.of(json);System.out.println(obj1.getData().getA());// Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.example.ParseJson}}

这里面的bug是,代码编译是可以的,但是一运行,就报ClassCastException

解决办法就是 别这么写了,com.alibaba.fastjson.TypeReference不能用泛型。

关键字:com.alibaba.fastjson.TypeReference的错误使用-----加泛型

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: