jackson序列化 属性 get 字段不对应

在jackson序列化对象时,由于其在源码中增加了一个可见性判断,会默认只序列化public修饰的字段和方法,造成一个可能存在的问题是你字段明明是CId,但是自动生成的get方法是getCId的话,jackson会将字段序列化成cid,造成一个反序列失败的问题(2.0.2到最新2.9.6版本测试),附上代码:

    

public class Test {
    public static void main(String[] args) throws IOException {
        Student stu = new Student();
        stu.setCId("王者");
        stu.setAge(12);
        ObjectMapper map = new ObjectMapper();
        //map.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        //map.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
        String json = map.writeValueAsString(stu);
        System.out.println(json);
    }
}


class Student implements Serializable {

    private static final long serialVersionUID = 1L;
    private String CId;
    private int age;

    public String getCId() {
        return CId;
    }

    public void setCId(String CId) {
        this.CId = CId;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

附上运行结果:

解决办法:jackson换成fastjson,或者将我上面代码中贴出来的注释去掉就好(全部字段可见,不对get方法进行序列化)

有兴趣的可以研究下其源码!

猜你喜欢

转载自my.oschina.net/u/3770892/blog/1928385