Json – Howto use Spring Resttemplate with JSON only

httpjsonresttemplatespring

I have a rest-service which provides information in XML or JSON. I connect my application to this service with Spring Resttemplate. Unfortunately my responses are all in XML instead of the prefered JSON format. My analysis of the requests is, that Spring Resttemplate sends the request with the following Accept-Header:

Accept: application/xml, text/xml, application/*+xml, application/json

My rest-service response with the first accepted type. This is allways application/xml.

How can I change the Accept-Types so that I only get json responses? Are there some properties for this in the bean-definition of RestTemplate?

I use Spring 3.1 for this.

Best Answer

You need to set a list of HttpMessageConverters available to RestTemplate in order to override the default one:

 RestTemplate rest = new RestTemplate();
 rest.setMessageConverters(Arrays.asList(new MappingJacksonHttpMessageConverter()));

If you define RestTemplate in XML, do the same thing in XML syntax.