在 Setter 或 Getter 上应用 @JsonProperty,而不是两者

Apply @JsonProperty on either Setter OR Getter, not both

我有这个class:

public class Foo {
    private int bar;
    public int getBar() {
        return this.bar;
    }
    @JsonProperty("baaaaar")
    public setBar(int bar) {
        this.bar = bar;
    }
}

现在如果我序列化它,我会得到以下结果:{"baaaaar": 0} 这对我来说似乎很奇怪,因为我只将 @JsonProperty 应用于 Setter。我认为 Getter 会保留其默认行为,即使用 属性 名称,而“baaaaar”只会用于反序列化。 有解决办法吗,还是我必须明确地将 @JsonProperty("bar") 添加到 Getter 中?

默认情况下 getter setter 上的单个 @JsonProperty 会为两者设置 属性。这确实允许您为整个应用程序重命名 属性
正如 this answer 中提到的,如果您希望它们具有不同的值,例如

,则需要同时设置 @JsonProperty
public class Foo {
    private int bar;

    @JsonProperty("bar") // Serialization
    public int getBar() {
        return this.bar;
    }

    @JsonProperty("baaaaar") // Deserialization
    public setBar(int bar) {
        this.bar = bar;
    }
}

编辑 1:

您可以在 documentation and the access properties 之后使用 @JsonProperty(access = WRITE_ONLY)