Jackson also needs getter methods to correctly serialize a bean property using @JsonCreator

99封情书 提交于 2021-02-05 07:36:18

问题


I am using Jackson to serialize some beans into JSON, inside an application that is using Spring Boot 1.5.

I noticed that to serialize a bean using the @JsonCreator correctly, I have to declare the getter method for each property, plus the @JsonProperty annotation.

public class Person {
    private final String name;
    private final int age;

    @JsonCreator
    public Person(@JsonProperty("name") String name, 
                  @JsonProperty("age") int age) {
       this.name = name;
       this.age = age;
    }

    public String getName() {
        return this.name;
    }
    public int getAge() {
        return this.age;
    }
}

If I remove methods getName and getAge, Jackson does not serialize the associated propertiy. Why does Jackson also need the getter methods?


回答1:


Jackson uses reflection to access private and protected properties. As soon as you delete the getter, Jackson doesn't know how to serialize/deserialize the properties (=your private fields). The used @JsonProperty annotations of the constructor won't help Jackson to find the properties while compile time as your constructor will be used at runtime.

Unintuitively, the getter also makes the private field deserializable as well – because once it has a getter, the field is considered a property.

Paraschiv, Eugen - "Jackson – Decide What Fields Get Serialized/Deserialized"



来源:https://stackoverflow.com/questions/49800779/jackson-also-needs-getter-methods-to-correctly-serialize-a-bean-property-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!