fastjson反序列化带有get没有set的list字段,没有值

反序列化带有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/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值