Custom filter attributes in Jackson when serializing

First use the @JsonFilter jackson annotation where you define an id of the filter

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonProperty;

public class ComparisonResultBulk implements Serializable {

  //other fields ignored for brevity

  private String maxLatencyMillis;

  private List<ComparisonResult> comparisonResults;

  private Integer notComparableResultsSize;

  private List<ComparisonResult> notComparableResults;

Then create a filterProvider, for example a SimpleFilterProvider for the id where you set the filter options.

In the example below everything is serialized except two properties with the help of SimpleBeanPropertyFilter.serializeAllExcept() method (serializeAll() is also present, and the opposite SimpleBeanPropertyFilter.filterOutAllExcept("individual_comparison_results", "not_comparable_results") which would serialize only these properties). In the end set the filterProvider set to the ObjectMapper where you serialize your object:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

private ComparisonReport generateReport(ComparisonResultBulk comparisonResultBulk)
      throws JsonProcessingException {
    ComparisonReport comparisonReport = new ComparisonReport();

    ObjectMapper mapper = new ObjectMapper();
    SimpleFilterProvider filterProvider = new SimpleFilterProvider();
    filterProvider.addFilter("IndividualComparisonResultsFilter", SimpleBeanPropertyFilter.serializeAllExcept("individual_comparison_results", "not_comparable_results"));


    return comparisonReport;

Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

Mongoose schema field from list of strings (enum)

Mongoose schema field from list of strings (enum) code snippet Continue reading

Set value of input field in angular template

Published on December 14, 2022

How to use jest test.each function

Published on December 14, 2022