Skip to content
Advertisement

How do you restrict custom ObjectMapper serializer to specific generic type

I would like to use a custom serializer for Maps, but only if they are <String, String> maps. I attempted to register a StdSerializer<Map,String, String>> following the advice in this post like so:

JavaScript

My Serializer looks as follows:

JavaScript

This works fine on Map<String, String> objects, but unfortunately it also gets called for other maps as well. How does one restrict a custom serializer to specific generic types?

Advertisement

Answer

Thanks to the comment by @shmosel, I’ve identified that the following solution appears to allow us to intercept the serializer assignment by using a SerializerModifier.

JavaScript

Then instead of registering the MapSerializer directly in the module, you register the modifier instead:

JavaScript

Now the modifier gets checked for each Map and either returns the custom serializer or the default serializer depending on the object’s type properties.

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