杰克逊@JsonGetter 和@JsonSetter 是如何工作的

How does jackson @JsonGetter and @JsonSetter work

我使用的是jackson 2.10.0 (https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.10.0),下面是一个简单的测试用例

Person class定义如下,对于setter,我使用了@JsonSetter注解,getter没有使用@JsonGetter,

import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    @JsonSetter("first_name")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @JsonSetter("last_name")
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

然后,我创建一个 Person 对象,并将其序列化为字符串,

import com.fasterxml.jackson.databind.ObjectMapper;


public class Person3Test2 {
    public static void main(String[] args) throws Exception {
        Person p = new Person();
        p.setFirstName("abc");
        p.setLastName("def");
        String str = new ObjectMapper().writeValueAsString(p);
        System.out.println(str);
    }
}

它会调用Person的getters,因为它没有使用@JsonGetter,所以我认为输出应该是

{"firstName":"abc","lastName":"def"}

但是,我惊讶地发现它是:

{"first_name":"abc","last_name":"def"}

看起来@JsonSetter 已经影响了 getter 输出,我想问一下这里的行为是什么。

@JsonSetter 将在序列化期间生效 here 是 github 问题,如果您想要不同的名称,只需在 get 方法上使用另一个注释 @JsonGetter

Documentation may be wrong; @JsonSetter does not only affect deserialization. While it can indeed be used for asymmetric naming (similar to @JsonProperty itself with "split" annotation), its scope is not limited. It may have been at some point, but after unification of property handling (in 1.8 or so), there is less separation between various property accessors.

I can review Javadocs to make it clear that none of annotations is strictly limited in scope -- some may only be relevant to one or the other, but none is intentionally separated.