How to add a MediaType to the MappingJackson2HttpMessageConverter instead of the RestTemplate

3.1k Views Asked by At

My question is very similar to How to change MediaType for MappingJacksonHttpMessageConverter in OAuth2RestTemplate but different in many ways.

I am using Spring 4 with SprintBoot. I want to use RestTemplate to query a Zimbra web services. The web service returns "JSON SOAP". It's really just JSON response in a format of a SOAP message.

Unfortunately, the response comes back as text/javascript; charset=utf-8 so the Message Converter fails as it does not find any converter for that media type.

How do I tell MappingJackson2HttpMessageConverter to consider this content type the same as regular JSON?

1

There are 1 best solutions below

2
On BEST ANSWER

After much looking, I found the solution to this problem. When one calls new RestTemplate (), a whole bunch of default HttpMessageConverters are created and loaded. This does not use any Spring beans.

So if like me you want to let the RestTemplate get configured with all its default but just add the necessary content type to the list, you can do the following:

  RestTemplate myRest = new RestTemplate ();
  for (HttpMessageConverter<?> myConverter : myRest.getMessageConverters ()) {
     if (myConverter instanceof MappingJackson2HttpMessageConverter) {
        List<MediaType> myMediaTypes = new ArrayList<MediaType> ();
        myMediaTypes.addAll (myConverter.getSupportedMediaTypes ());
        myMediaTypes.add (MediaType.parseMediaType ("text/javascript; charset=utf-8"));
        ((MappingJackson2HttpMessageConverter) myConverter).setSupportedMediaTypes (myMediaTypes);
     }
  }