反序列化带有get方法的list字段
但是对于对象中带有get方法的list字段,fastjson的处理:
通过get方法获取list或map,如果是null不会处理。
以下带来。com.alibaba.fastjson.parser.deserializer.FieldDeserializer类 setValue方法片段。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| else if (Map.class.isAssignableFrom(method.getReturnType())) {
Map map = (Map) method.invoke(object);
if (map != null) {
if (map == Collections.emptyMap()
|| map.getClass().getName().startsWith("java.util.Collections$Unmodifiable")) {
// skip
return;
}
map.putAll((Map) value);
}
} else {
Collection collection = (Collection) method.invoke(object);
if (collection != null && value != null) {
if (collection == Collections.emptySet()
|| collection == Collections.emptyList()
|| collection.getClass().getName().startsWith("java.util.Collections$Unmodifiable")) {
// skip
return;
}
collection.clear();
collection.addAll((Collection) value);
}
}
|
所以以下例子反序列化出来的ids属性为null。
1
2
3
4
5
6
7
8
9
10
11
12
13
| public class Test {
private int id;
private List<Integer> ids;
public int getId() {
return id;
}
public List<Integer> getIds() {
return ids;
}
}
|
1
2
3
4
5
6
7
8
| String msg="[" +
"{" +
"\"id\":1," +
"\"ids\":[1,2]" +
"}" +
"]";
Test obj = JSON.parseObject(msg, new TypeReference<Test>() {
}.getType(), Feature.SupportNonPublicField);
|
解决方法
//ParserConfig 添加true参数,开启只基于字段进行反序列化。
1
2
| JSON.parseObject(msg,ew TypeReference<Test>() {
}.getType(),
new ParserConfig(true));
|
设置了fieldBased,反序列化处理来ids就有值了
详细:https://wujiazhen2.github.io/2018/10/27/fastjson%E4%BD%BF%E7%94%A8%E7%BB%8F%E9%AA%8C/