You should write a custom Jackson filter which would filter out a POJO property depending on other property value. You should override the PropertyFilter.serializeAsField()
method to get access to the instance of the serialized object. Here is an example:
public class JacksonFilter2 {
@JsonFilter("filter")
public static class Bar {
public final int id;
@JsonIgnore
public final boolean ignoreId;
public final String name;
public Bar(int id, boolean ignoreId, String name) {
this.id = id;
this.ignoreId = ignoreId;
this.name = name;
}
}
public static class ExcludeIdFilter extends SimpleBeanPropertyFilter {
@Override
protected boolean include(BeanPropertyWriter writer) {
return true;
}
@Override
protected boolean include(PropertyWriter writer) {
return true;
}
@Override
public void serializeAsField(Object pojo,
JsonGenerator jgen,
SerializerProvider provider,
PropertyWriter writer) throws Exception {
if (pojo instanceof Bar
&& "id".equals(writer.getName())
&& ((Bar) pojo).ignoreId) {
writer.serializeAsOmittedField(pojo, jgen, provider);
} else {
super.serializeAsField(pojo, jgen, provider, writer);
}
}
}
public static void main(String[] args) throws JsonProcessingException {
List<Bar> bars = Arrays.asList(new Bar(1, false, "one"), new Bar(2, true, "two"));
ObjectMapper mapper = new ObjectMapper();
mapper.setFilters(new SimpleFilterProvider().addFilter("filter", new ExcludeIdFilter()));
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bars));
}
}
Output:
[ {
"id" : 1,
"name" : "one"
}, {
"name" : "two"
} ]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…