2

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?

Ala Abid
  • 2,256
  • 23
  • 35

1 Answers1

1

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.

IQbrod
  • 2,060
  • 1
  • 6
  • 28
  • Thanks for your answer, indeed that's what I found out after some research, but I thought there could potentially be another way, something like, but not exactly, JsonProperty "access" parameter. – Ala Abid Oct 07 '20 at 13:23
  • There might be, I just checked the doc. Check my Edit. – IQbrod Oct 07 '20 at 13:25
  • @AlaAbid you might use `WRITE_ONLY` for deserialization or `READ_ONLY` for serialization. – IQbrod Oct 07 '20 at 13:29
  • Unfortunately it doesn't work somehow. When field itself is no longer visible in the response. – saran3h Nov 12 '21 at 14:38
  • @saran3h you need to explicitly allow null values in your serializer. Check this [answer](https://stackoverflow.com/a/6507965/11825162) – IQbrod Nov 15 '21 at 10:39