I need to add @JsonIgnore
annotated fields while serializing an object by Jackson ObjectMapper
. I know you may offer me to remove the @JsonIgnore
You can define a SimpleBeanPropertyFilter and FilterProvider.
First annotate your class with custom filter like this:
@JsonFilter("firstFilter")
public class MyDtoWithFilter {
private String name;
private String anotherName;
private SecondDtoWithFilter dtoWith;
// get set ....
}
@JsonFilter("secondFilter")
public class SecondDtoWithFilter{
private long id;
private String secondName;
}
and this is how you will dynamically serialise your object.
ObjectMapper mapper = new ObjectMapper();
// Field that not to be serialised.
SimpleBeanPropertyFilter firstFilter = SimpleBeanPropertyFilter.serializeAllExcept("anotherName");
SimpleBeanPropertyFilter secondFilter = SimpleBeanPropertyFilter.serializeAllExcept("secondName");
FilterProvider filters = new SimpleFilterProvider().addFilter("firstFilter", firstFilter).addFilter("secondFilter", secondFilter);
MyDtoWithFilter dtoObject = new MyDtoWithFilter();
String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);