-
Notifications
You must be signed in to change notification settings - Fork 546
Closed
Description
问题描述
ObjectReaderImplList中239行使用了Collections.emptyList(),导致空List反序列化后向其中添加元素时报java.lang.UnsupportedOperationException异常
环境信息
- 版本信息:[Fastjson2 2.0.40]
重现步骤
参见以下bug复现代码
public class App {
public static void main(String[] args) {
List<Person> sourceList = new ArrayList<>();
// sourceList.add(new Person("zhangsan"));
Map<String, Object> source = new HashMap<>();
source.put("data", sourceList);
String json = JSON.toJSONString(source);
System.out.println(json);
JSONObject target = JSON.parseObject(json);
Type type = getType();
List<Person> targetList = target.getObject("data", type);
System.out.println(targetList.getClass().getName());
targetList.add(new Person("lisi"));
System.out.println(JSON.toJSONString(targetList));
}
public static Type getType() {
try {
App app = new App();
Method method = app.getClass().getMethod("test");
return method.getGenericReturnType();
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public List<Person> test() {
return new ArrayList<>();
}
public static class Person {
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}期待的正确结果
空List反序列化后可以正常向其中添加元素。
全面排查并仔细评估所有使用了Collections.emptyList()和Collections.emptySet()的地方,有类似问题的地方建议一并修改。
相关日志输出
以上bug复现代码日志输出如下
{"data":[]}
java.util.Collections$EmptyList
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.AbstractList.add(AbstractList.java:153)
at java.base/java.util.AbstractList.add(AbstractList.java:111)
at com.dcr.demo.App.main(App.java:34)
附加信息
我使用fastjson2做Openfeign接口的序列化及反序列化,当Openfeign接口方法返回值不为空时,向list中添加元素不报异常。当返回空List后,再向list中添加元素时会报UnsupportedOperationException异常。