Skip to content
Advertisement

Dynamic serialization using Jackson – removing fields with specific annotations

Went down a path of creating an annotation that would dynamic determine whether a field should be serialized or not.

The annotation’s implementation is as follows:

JavaScript

Now the code for the Serializer:

JavaScript

A little bit of code to show how it works:

JavaScript

And the output is as follows:

JavaScript

How do I get the field pin to be removed from the serialization instead of it being null? Obviously setting the mapper’s properties was of very little user in such a context. Any suggestions? Thoughts? Maybe the whole thing is a bad idea?

Ideally I should be able to see the following:

JavaScript

Advertisement

Answer

It’s not clear whether you want to ignore a given property statically or dynamically. Anyways, looks like you have over-engineered it.

First of all, I want to make sure that you came across @JsonIgnore before. If it doesn’t suit your needs, you could define your custom ignore annotation as following:

JavaScript

Then pick the approach that best suit your needs:

Approach #1

Extend JacksonAnnotationIntrospector and override the method that checks for the ignore marker:

JavaScript

Configure ObjectMapper to use your annotation introspector:

JavaScript

The annotation introspection occurs only once per class so you can not dynamically change the criteria you use (if any). A similar example can be seen in this answer.

Approach #2

Extend BeanSerializerModifier to modify the properties that will be serialized:

JavaScript

Then add it to a Module and register it to your ObjectMapper:

JavaScript

This approach allows you to ignore properties dynamically.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement