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

huangapple go评论49阅读模式
英文:

Apply @JsonProperty on either Setter OR Getter, not both

问题

我有这个类:

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

现在,如果我对此进行序列化,我将会得到以下结果:{"baaaaar": 0} 这对我来说似乎很奇怪,因为我只将 @JsonProperty 应用于 Setter 方法。我原以为 Getter 会保持其默认行为,即使用属性名,而 "baaaaar" 只会在反序列化时使用。这个问题有解决办法吗,还是我必须在 Getter 方法中显式添加 @JsonProperty("bar")

英文:

I have this class:

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

Now if I serialize this, I would get the following result: {"baaaaar": 0} which seems odd to me as I only applied @JsonProperty to the Setter. I thought the Getter would keep its default behavior, that is to use the property name, and "baaaaar" would only be used for deserialisation.
Is there a solution to this, or do I have to explicitly add @JsonProperty("bar") to the Getter as well?

答案1

得分: 1

默认情况下,对getter 或者 setter应用单个@JsonProperty会同时设置两者的属性。这允许您为整个应用程序重命名属性。正如在此回答中所提到的,如果您希望它们具有不同的值,您需要同时设置两个@JsonProperty,如下所示:

public class Foo {
    private int bar;

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

    @JsonProperty("baaaaar") // 反序列化
    public void setBar(int bar) {
        this.bar = bar;
    }
}

编辑 1:

您可以根据文档访问属性使用@JsonProperty(access = WRITE_ONLY)

英文:

By default a single @JsonProperty on getter OR setter does set the property for both. This does allow you to rename a property for your whole application
As mentionned on this answer you need to set both @JsonProperty if you want them to have different values like

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

EDIT 1 :

You might use @JsonProperty(access = WRITE_ONLY) following the documentation and the access properties.

huangapple
  • 本文由 发表于 2020年10月7日 19:35:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64243180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定