Filter out certain fields during deserialization in Jackson?

45 Views Asked by At

I have the following class that I deserialize incoming JSON:

data class Foo(
    val result: List<Map<String, Any>>,
)

I want to filter out specific keys from it.

For instance, if Map contains the key foo, I want to remove it.

I know that there are @JsonIgnore and @JsonIgnoreProperties annotations, but I don't think that they're useful on a Map.

Currently, I filter the map, but I wonder if there is a more Jackson-specific way to do this (e.g. using filters).

1

There are 1 best solutions below

0
Chaosfire On BEST ANSWER

You can still add the annotations using mixins - more specifically ObjectMapper.addMixin(target, mixinSource).

Method to use for adding mix-in annotations to use for augmenting specified class or interface. All annotations from mixinSource are taken to override annotations that target (or its supertypes) has.

Let's say this is your mixin:

@JsonIgnoreProperties({"k1", "k2", "k3"})
record MapMixin() {
}

All annotations on MapMixin will be added to Maps using the method above:

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Map.class, MapMixin.class);

Map<String, Object> map = Map.of(
    "qwe", 11, 
    "k3", "v",
    "rty", "t", 
    "k2", 3
);
System.out.println(mapper.writeValueAsString(map));

The above example will serialize the map as:

{
  "rty": "t",
  "qwe": 11
}