Explain Codes LogoExplain Codes Logo

How can I tell jackson to ignore a property for which I don't have control over the source code?

java
serialization
jackson
deserialization
Anton ShumikhinbyAnton Shumikhin·Dec 7, 2024
TLDR

With Jackson, you can bypass the property serialization issue using a mixin with an @JsonIgnore annotation. Here's how:

@JsonIgnoreProperties({"propertyToIgnore"}) abstract class MyMixin {} ObjectMapper mapper = new ObjectMapper(); mapper.addMixIn(Target.class, MyMixin.class);

By using this configuration, Jackson will conveniently ignore propertyToIgnore during the serialization process of the Target class.

Customizing serialization without changing source code

If you are in a situation where you need to exclude certain elements from serialization but don't have control over the source code, don't worry! Jackson has got you covered. Let's look at a few possibilities:

  1. Ignore unknown properties: You can instruct the ObjectMapper to disregard unknown properties like this:

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Keep calm and ignore unknown properties.
  2. Additionally, you can use the @JsonIgnoreProperties annotation to ignore unpredicted properties at class level:

    @JsonIgnoreProperties(ignoreUnknown = true) // Avoid surprises with unexpected properties.

Employing mixins and filters to tackle serialization

Mixin to rule them all

Jackson lets you define a rule that applies to multiple classes. Enter setMixInResolver with MixInResolver implementation. This powerful approach allows you to define the logic for finding mix-in classes for target classes on the fly.

@JsonIgnoreProperties({"unwantedGlobalProperty"}) abstract class GlobalPropertyIgnoreMixIn {} mapper.setMixInResolver(new SimpleMixInResolver(null) { @Override public Class<?> findMixInClassFor(Class<?> cls) { // One mixin to rule them all 💍 return GlobalPropertyIgnoreMixIn.class; } });

Dynamic filtering using JsonFilter

Using a JsonFilter can bring even more flexibility to your filtering:

  1. Define your filter:

    @JsonFilter("yourFilter") abstract class YourBean {}
  2. Create your filter rule:

    SimpleFilterProvider filters = new SimpleFilterProvider().addFilter("yourFilter", SimpleBeanPropertyFilter.serializeAllExcept("propertyToIgnore"));
  3. Apply the filters using an ObjectWriter:

    ObjectWriter writer = mapper.writer(filters);

Guide to custom deserialization

Feel free to use @JsonCreator and @JsonProperty annotations to control deserialization:

class CustomDeserialized { private String property1; @JsonCreator public CustomDeserialized(@JsonProperty("property1") String prop1) { // handle with care 🎁 this.property1 = prop1; } }