-
Notifications
You must be signed in to change notification settings - Fork 550
Closed
Labels
bugSomething isn't workingSomething isn't working
Milestone
Description
问题描述
从fastjson 1.2.83升级到 fastjson2 2.0.7,原先代码使用JSON.parseObject()的方法抛异常
环境信息
- OS信息: Windows 10 专业版 20H2
- JDK信息: 1.8.0_311
- 版本信息: 2.0.7
重现步骤
运行以下main()方法,不改代码,升级fastjson2后,并不能返回预期的对象。会引起java.lang.ClassCastException
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Response <T extends AbstractResult> {
private T data;
}
public abstract class AbstractResult {
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result extends AbstractResult {
List<Item> items;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Item {
private String name;
}
public class Main {
public static void main(String[] args) {
Item item1 = new Item("item1");
Item item2 = new Item("item2");
Result result = new Result(Arrays.asList(item1, item2));
Response<Result> response = new Response<>(result);
String json = JSON.toJSONString(response);
System.out.println(fastJsonParse(json, Result.class));
System.out.println(fastJson2Parse(json, Result.class));
}
static <T extends AbstractResult> T fastJson2Parse(String json, Class<?> clazz) {
TypeReference<Response<T>> typeReference = new TypeReference<Response<T>>(clazz) {
};
Response<T> result = JSON.parseObject(json, typeReference);
return result.getData();
}
static <T extends AbstractResult> T fastJsonParse(String json, Class<?> clazz) {
com.alibaba.fastjson.TypeReference<Response<T>> typeReference = new com.alibaba.fastjson.TypeReference<Response<T>>(clazz) {
};
Response<T> result = com.alibaba.fastjson.JSON.parseObject(json, typeReference);
return result.getData();
}
}期待的正确结果
期望能升级fastjson2后,对原有代码影响更小
相关日志输出
Exception in thread "main" java.lang.ClassCastException: com.xxxxx.ResultA cannot be cast to com.xxxxx.Response
at com.xxxxx.Main.fastJson2Parse(Main.java:29)
at com.xxxxx.Main.main(Main.java:23)
附加信息
无
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't working