I'm writing a postback handler library for a service that has some odd JSON mapping practices. I can very easily configure a custom Jackson ObjectMapper
to handle the mapping, but if I register a Spring MVC message converter with that mapper, it applies the mapping (which is incorrect for the rest of the JSON I'm dealing with) to all incoming requests.
There are a handful of manual approaches I can apply to hand-decode these messages, but it would be much cleaner to have the Spring type-conversion service handle it in the request pipeline.
Is there a feasible way to attach a custom message converter to a specific controller, handler method, or mapping string/template/prefix?
Spring MVC (client and server side) uses HttpMessageConverters to negotiate content conversion in an HTTP exchange. If Jackson is on the classpath you already get a default converter with a vanilla ObjectMapper .
Http Message Converter is responsible for serializing Java Object to JSON/XML data representation and deserializing JSON/XML data representation to Java Object.
The @EnableWebMvc annotation is used for enabling Spring MVC in an application and works by importing the Spring MVC Configuration from WebMvcConfigurationSupport.
I had a similar situation - I wanted to create custom @ResponseBody
equivalent that would allow me to configure certain aspects of JSON serialization (in my example, I wanted JSON values optionally html encoded). I ended up creating custom @JsonResponseBody
annotation which would cause spring mvc to use differently configured Jackson message converter for methods annotated with it.
I had to extend Spring's AbstractMessageConverterMethodProcessor
to register custom handling for my custom annotation and then I needed to register my CustomAbstractMessageConverterMethodProcessor
with spring framework by adding it to RequestMappingHandlerAdapter
's list of handlers. This was also tricky, because if you use xml config you have to do it via BeanPostProcessor
.
At the time I was attempting this (year ago, Spring 3.1), I didn't find any easier way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With