Java JsonIgnore-class And Method Code Example
Here is an example of using the JsonIgnore annotation from the Apache Commons IO library to ignore a field when serializing an object to JSON:
import org.apache.commons.io.output.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties({"fieldToIgnore"})
public class MyClass {
private String fieldToIgnore;
private String fieldToKeep;
public MyClass(String fieldToIgnore, String fieldToKeep) {
this.fieldToIgnore = fieldToIgnore;
this.fieldToKeep = fieldToKeep;
}
public String getFieldToKeep() {
return fieldToKeep;
}
@JsonIgnore
public String getFieldToIgnore() {
return fieldToIgnore;
}
}
In this example, the fieldToIgnore is annotated with @JsonIgnore which will be ignored during serialization. Also, it is annotated with @JsonIgnoreProperties({"fieldToIgnore"}) at class level to ignore the field.
Make sure that you are using jackson as serializer.