Jackson 还需要 getter 方法来使用 @JsonCreator 正确序列化 bean 属性

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

我在使用 Spring Boot 1.5.

的应用程序中使用 Jackson 将一些 bean 序列化为 JSON

我注意到要正确使用 @JsonCreator 序列化一个 bean,我必须为每个 属性 声明 getter 方法,加上 @JsonProperty 注释。

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;
    }
}

如果我删除方法 getNamegetAge, Jackson 不会序列化关联的属性。为什么 Jackson 还需要 getter 方法?

Jackson 使用反射来访问私有和受保护的属性。 一旦删除 getter,Jackson 就不知道如何 serialize/deserialize 属性(=您的私有字段)。 构造函数使用的 @JsonProperty 注释不会帮助 Jackson 在编译时找到属性,因为您的构造函数将在运行时使用。

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

欧根·帕拉斯基夫 - "Jackson – Decide What Fields Get Serialized/Deserialized"