Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify message converters for single Spring Controller

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?

like image 562
chrylis -cautiouslyoptimistic- Avatar asked May 07 '14 09:05

chrylis -cautiouslyoptimistic-


People also ask

Which of the following HTTP message converters are supported by Spring MVC?

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 .

What is an Httpmessage converter in spring rest?

Http Message Converter is responsible for serializing Java Object to JSON/XML data representation and deserializing JSON/XML data representation to Java Object.

What is @EnableWebMvc?

The @EnableWebMvc annotation is used for enabling Spring MVC in an application and works by importing the Spring MVC Configuration from WebMvcConfigurationSupport.


1 Answers

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 @JsonResponseBodyannotation which would cause spring mvc to use differently configured Jackson message converter for methods annotated with it.

I had to extend Spring's AbstractMessageConverterMethodProcessorto 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.

like image 166
Krešimir Nesek Avatar answered Sep 28 '22 20:09

Krešimir Nesek