Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the real 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.

like image 502
yafiet andebrhan Avatar asked Dec 18 '22 15:12

yafiet andebrhan


1 Answers

@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"}

like image 105
LHCHIN Avatar answered Jan 06 '23 14:01

LHCHIN