如何仅使用Spring Resttemplate与JSON

Adr*_*ian 10 spring json http resttemplate

我有一个rest-service,它提供XML或JSON信息.我使用Spring Resttemplate将我的应用程序连接到此服务.不幸的是,我的回复都是XML而不是首选的JSON格式.我对请求的分析是,Spring Resttemplate使用以下Accept-Header发送请求:

Accept: application/xml, text/xml, application/*+xml, application/json
Run Code Online (Sandbox Code Playgroud)

我的休息服务响应与第一个接受的类型.这是allways application/xml.

如何更改Accept-Types以便我只获得json响应?在RestTemplate的bean定义中是否有一些属性?

我使用Spring 3.1.

axt*_*avt 13

您需要设置HttpMessageConverter可用的列表RestTemplate以覆盖默认值:

 RestTemplate rest = new RestTemplate();
 rest.setMessageConverters(Arrays.asList(new MappingJacksonHttpMessageConverter()));
Run Code Online (Sandbox Code Playgroud)

如果您RestTemplate使用XML 定义,请在XML语法中执行相同的操作.

  • 对于新版本,虽然它是:MappingJackson2HttpMessageConverter.class (5认同)
  • 我已经定义了这样的其余模板:<bean id ="restTemplate"class ="org.springframework.web.client.RestTemplate"> <property name ="messageConverters"> <list> <bean class ="org.springframework. http.converter.json.MappingJacksonHttpMessageConverte r"/> </ list> </ property> </ bean>但是Accpet标题仍然是:接受:application/xml,text/xml,application/*+ xml,application/json (2认同)