Inject data to nested serializers in Jackson

We sometimes need to tunnel information to a nested serializer and do it from the top level.

Let’s take the following example of some Shape objects which are nested in a Drawing object.

We will be serializing the drawing object using Jackson, so let’s define the appropriate serializers.

Now, let’s say that from the Drawing serializer we would like to inject some information into the Shape serializer. But, as you see Jackson never gives us an instance of the Shape serializer so it won’t be possible to change its members.

So how do we do this? Here come the attributes. These ones are set on the SerializerProvider object and can be later retrieved from a more nested serializer.

As example, let’s say we want to inject an attribute, that, when true, will make the Shape serializer output the name as upper case.

We inject the attribute in the Drawing serializer.

Now from the nested serializer we can retrieve the value of the attribute which was injected at top level.

 

Leave a Reply

Your email address will not be published. Required fields are marked *