我也遇到过其他类似的问题,但都不起作用。
所有我的JSON API返回的都作为响应,默认情况下是
由于一些XML API,我不得不添加jackson-xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
现在默认不带accept头的“”所有响应都是。
我希望有JSON作为默认的响应格式。
如这里的文档所述:
https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc
我实现了以下配置:
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true)
.useJaf(false).defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
}
案例1:,如果我创建ignoreAcceptHeader(true)
,那么一切都是JSON,即使是返回JSON的XML API也是如此。
情况2:,当ignoreAcceptHeader(false)
为默认值时,则为XML。
我忘了说我的API是这样的:
@RequestMapping(value = "/getXml", method = RequestMethod.GET)
public ResponseEntity<String> getXml( HttpServletRequest request)
throws JAXBException {
return returnXml();
}
我在这里完全迷惑了,我想要的是缺省(没有AcceptHeader)应该是JSON。(API以字符串形式返回XML )
当Accept Header:"Application/ XML“被定义时,那么响应应该是XML。
任何建议都会有很大帮助。
谢谢。
发布于 2016-12-08 20:14:45
一般来说,如果你想得到json响应,你需要一个jackson-databind模块:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${json-jackson-version}</version>
</dependency>
然后,您必须在配置中定义一个MappingJackson2HttpMessageConverter
:
@Configuration
@EnableWebMvc
public class WebAppMainConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
[..]
super.configureMessageConverters(converters);
}
[...]
}
在您的例子中,您可以实现自己的AbstractGenericHttpMessageConverter,这样您就可以根据媒体类型在不同的具体转换器之间切换。
检查AbstractGenericHttpMessageConverter#writeInternal(..)
方法
发布于 2017-11-15 19:14:00
对我来说,添加
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
}
}
解决了这个问题。
现在,默认情况下,如果请求中没有Accept
头,则所有RestController
都返回JSON。另外,如果传递了XML头,则结果为Accept: application/xml
。
另外,值得一读的是:https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc
发布于 2016-12-08 18:21:39
由于您已经将ignoreAcceptHeader设置为true,并将favorPathExtension设置为false,spring将依赖于其他替代方案来进行内容协商。意味着它将查看您已配置XML和JSON的URL参数
因此,正如@stan pointed /getXml?mediaType=xml
应该返回xml响应,否则它将缺省为json(defaultContentType(MediaType.APPLICATION_JSON))
https://stackoverflow.com/questions/41036377
复制相似问题