使用fastJson踩坑记录汇总

坑1-属性方法命名问题

问题表象

在使用fastjson工具把一个领域DTO对象转为 JSON 字符串,结果导致了非属性的 get 方法被调用了,此时延时加载所需的 bean 还没有注入,导致出现空指针。

场景复现

先构建一个一个学生类,里面只有一个属性,name

public class Student {
    
    
   private String name;
   public String getValue() {
    
    
       return "testGetValue";
   }
      public String setName(String name) {
    
    
       this.name = name;
   }
}

用fastjson解析

public static void main(String[] args) {
    
    
   Student student = new Student();
   student.setName("zhansan");
   System.out.println(JSON.toJSONString(student));
}

结果将会打印 :

{“name”:“zhansan”,“value”:“testGetValue”}

问题根因

Fastjson 在序列化时会检查类的方法,并将符合一定规则的方法作为属性处理。具体规则是方法名以 get 或 is 开头,并且满足 Java Bean 的命名规范,Fastjson 将其识别为属性,并调用方法获取属性的值。

坑2-后面有空补充

问题表象

场景复现

问题根因

猜你喜欢

转载自blog.csdn.net/qq_39463175/article/details/131425917