Custom HttpMessageConverter to accept JSON response with wrong content type

I am using a web service that is serves JSONP. The response content type I get from it is “text/javascript” (which is non-standard, I believe it should be “application/javascript” for jsonp). However, the service can also return JSON, and I am using Spring’s RestTemplate to call this service to return JSON.  This is the error I get when I try to convert it into Map[] objects via rest.getForEntity(targetUrl, Map[].class);

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [LMap[].class;] and content type [text/javascript]

Problem:
Web service returning wrong content type, causing RestClientException to be thrown, because Spring does not know how to convert such response into the class you want.

Solution:
Because I know the result will be JSON, I created a custom HttpMessageConverter that behaves the same as MappingJacksonHttpMessageConverter, but supports all content types.

public class MappingAnyJsonHttpMessageConverter
  extends MappingJacksonHttpMessageConverter {

  public MappingAnyJsonHttpMessageConverter() {
    List list = new ArrayList(1);
    list.add(MediaType.ALL);
    this.setSupportedMediaTypes(list);
  }
}

Now, tell my RestTemplate to use this message converter

RestTemplate rest = new RestTemplate();
List<HttpMessageConverter<?>> msgConverters =
  new ArrayList<HttpMessageConverter<?>>(1);
msgConverters.add(new MappingAnyJsonHttpMessageConverter());
rest.setMessageConverters(msgConverters);

ResponseEntity<Map[]> response =
rest.getForEntity(targetUrl, Map[].class);
Map[] jsonResult = response.getBody();

No more errors 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s