java - jackson @JsonGetter和@JsonSetter如何工作

标签 java jackson jackson-databind jackson2

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

Person类定义如下,对于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 的 getter,因为它不使用 @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.

关于java - jackson @JsonGetter和@JsonSetter如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58600830/

相关文章:

java - 带有空白字符串的Jackson com.fasterxml.jackson.databind.exc.MismatchedInputException

java - jackson 转发属性而不是外部对象

java - 如何在 JTextArea 中添加可点击的 URL?

java - 设备上安装的应用程序未显示在应用程序菜单中

java - 编译项目时出现错误 : Unable to locate Spring NamespaceHandler

java - Jackson 将 Object 序列化为 JSON 到 base64(没有无限循环)

java - 使用 POJO 字段名将 POJO 转换为 JsonNode

java - 如何动画 View 的高度?

java - 使用 Jackson 解析 ElasticSearch 输出

java - Jackson:有没有办法在 boolean 反序列化中忽略 0/1?