反序列化帶有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); |
解決方法
1 2 3 4 5 6 7 |
public class MyParserConfig extends ParserConfig{ public MyParserConfig(){ //開啓只基於字段進行反序列化。 super(true) } } ` |
1 2 |
JSON.parseObject(msg,ew TypeReference<Test>() { }.getType(),new MyParserConfig()); |
設置了fieldBased,反序列化處理來ids就有值了