Apply @JsonProperty on either Setter OR Getter, not both

Viewed 1509

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 Answers

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.

Related