0

I understand that JsonProperty is used to map the variable to JSON key if the key is different from the variable.

Below is my sample POJO:-

 public class JsonProperty {
        @JsonProperty("studentId")  //---------------variable
        private String id;
        
        @JsonProperty("studentId")  //---------------getter
        public String getIdValue() {
            return id;
        }
        
        @JsonProperty("studentId")  //---------------setter
        public void setIdValue(String id) {
            this.id = id;
        }
}

JSON String: {"studentId" : "so1"}

Let's say that we are saving in DB using some JDBC code. I observed the below changes but could not accurately understand the behavior.

  1. If @JsonProperty("studentId") is not used on a variable, getter and setter. observation: Noting is stored on DB.

  2. If @JsonProperty("studentId") is used on variable alone. Observation: {"idValue" : "so1"} is stored in DB.

  3. If @JsonProperty("studentId") is used on setter or getter. Observation: {"studentId" : "so1"} is stored in DB.

So, Could you explain what is the actual behavior that happens when we use JsonProperty on variable, getter and setter???

Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
Rajeev
  • 442
  • 1
  • 5
  • 18
  • duplicate of https://stackoverflow.com/questions/11526874/jsonproperty-annotation-on-field-as-well-as-getter-setter. There is an order of precedence between the different annotations – JP Moresmau May 11 '21 at 13:21

1 Answers1

-1

One of the simplest explanation is: @JsonProperty(name), tells Jackson ObjectMapper to map the JSON property name to the annotated Java field's name.

sultania23
  • 322
  • 3
  • 11