Fasterxml ObjectMapper does not exclude fileds from JSON

2.4k views Asked by At

I have been using codehaus for a while and the following code to exclude the fields from the JSON when serializing the same.

ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(Object.class, PropertyFilterMixIn.class);

SimpleBeanPropertyFilter propertyFilter = SimpleBeanPropertyFilter.serializeAllExcept(ignoreFieldNames);
FilterProvider simpleFilterProvider = new    SimpleFilterProvider().addFilter("PropertyFilter", propertyFilter);

ObjectWriter writer = mapper.writer(simpleFilterProvider);
String jsonContent = writer.writeValueAsString(obj);

I upgraded to fasterxml and changed the code as follows,

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Object.class, PropertyFilterMixIn.class);

SimpleBeanPropertyFilter propertyFilter = SimpleBeanPropertyFilter.serializeAllExcept(ignoreFieldNames);
FilterProvider simpleFilterProvider = new SimpleFilterProvider().addFilter("PropertyFilter", propertyFilter);
//mapper.getSerializationConfig().withFilters(simpleFilterProvider);

ObjectWriter writer = mapper.writer(simpleFilterProvider);
String jsonContent = writer.writeValueAsString(obj);

However, the above code is not working as expected. It does not respect the ignoreFieldNames at all and just returns all the fields in the object (without excluding the fields mentioned in the "ignoreFieldNames" (String array).

Any help would be greatly appreciated.

Thanks in advance.

1

There are 1 answers

4
Jan Cetkovsky On

You need to annotate your bean with your filter

@JsonFilter("PropertyFilter")
public class ClassImSerializing

or in case you can't, you can add it as a global mix in annotation

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Object.class, PropertyFilterMixIn.class);

@JsonFilter("PropertyFilter")
class PropertyFilterMixIn {

}