javajava-8jacksonjackson2

JsonIgnore on Field vs JsonIgnore on getter of a field in Jackson


What is the difference between JsonIgnore on Field vs JsonIgnore on a getter of a field in Jackson?


Solution

  • @JsonIgnore annotation is used to ignore fields from de-serialization and serialization, it can be put directly on the instance member or on its getter or its setter. The application of the annotation in any of these 3 points, leads to the total exclusion of the property from both the serialization and de-serialization processes (and this applies starting from Jackson 1.9; the version used in these examples is Jackson 2.4.3).

    Note: Before version 1.9, this annotation worked purely on method-by-method (or field-by-field) basis; annotation on one method or field did not imply ignoring other methods or fields

    Example

     import java.io.IOException;
    
     import com.fasterxml.jackson.annotation.JsonIgnore;
     import com.fasterxml.jackson.core.JsonParseException;
     import com.fasterxml.jackson.core.JsonProcessingException;
     import com.fasterxml.jackson.databind.JsonMappingException;
     import com.fasterxml.jackson.databind.ObjectMapper;
    
     class MyTestClass {
    
     private long id;
     private String name;
     private String notInterstingMember;
     private int anotherMember;
     private int forgetThisField;
    
     public long getId() {
        return this.id;
     }
    
     public void setId(long id) {
         this.id = id;
     }
    
     public String getName() {
         return this.name;
     }
    
     public void setName(String name) {
        this.name = name;
     }
    
     @JsonIgnore
     public String getNotInterstingMember() {
        return this.notInterstingMember;
     }
    
     public void setNotInterstingMember(String notInterstingMember) {
        this.notInterstingMember = notInterstingMember;
     }
    
     public int getAnotherMember() {
        return this.anotherMember;
     }
    
     public void setAnotherMember(int anotherMember) {
        this.anotherMember = anotherMember;
     }
    
     public int getForgetThisField() {
        return this.forgetThisField;
     }
    
     @JsonIgnore
     public void setForgetThisField(int forgetThisField) {
        this.forgetThisField = forgetThisField;
     }
    
     @Override
     public String toString() {
        return "MyTestClass [" + this.id + " , " +  this.name + ", " + this.notInterstingMember + ", " + this.anotherMember + ", " + this.forgetThisField + "]";
        }
    
      }
    

    Output:

     {"id":1,"name":"Test program","anotherMember":100}
     MyTestClass [1 , Test program, null, 100, 0]
    

    But still it is possible to change this behavior and make it asymmetric, for example to exclude a property only from the deserialization using the @JsonIgnore annotation together with another annotation called @JsonProperty.