'What is use of the annotation @JsonIgnore?

I'm joining tables with one to many cardinality, the classes I'm using refer to each other. And I'm using @JsonIgnore annotation with out understanding it deeply.



Solution 1:[1]

@JsonIgnore is used to ignore the logical property used in serialization and deserialization. @JsonIgnore can be used at setters, getters or fields.

If you add @JsonIgnore to a field or its getter method, the field is not going to be serialized.

Sample POJO:

class User {
    @JsonIgnore
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    @JsonIgnore
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }  
}

Sample code for serialization:

ObjectMapper mapper = new ObjectMapper();
User user = new User();
user.setId(2);
user.setName("Bob");
System.out.println(mapper.writeValueAsString(user));

Console output:

{"name":"Bob"}

Solution 2:[2]

When serializing your object into Json, the fields that are tagged with @JsonIgnore will not be included in the serialized Json object. This attribute is read by the Json serialize using reflection.

Solution 3:[3]

The Jackson's @JsonIgnore annotation can be placed on fields, getters/settess and constructor parameters mark a property to be ignored during the serialization to JSON (or deserialization from JSON). Refer to the Jackson annotations reference documentation for more details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ross Brigoli
Solution 3 cassiomolin