英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论