les*_*nar 11 spring spring-mvc spring-boot
我已经解决了其他类似问题,但对我来说没有任何效果.
默认情况下,我的所有API都将JSON作为响应返回:
由于一些XML API,我不得不添加jackson-xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
现在默认情况下" 没有接受标头"所有响应都是XML.
我想将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);
}
Run Code Online (Sandbox Code Playgroud)
案例1:如果我做了,ignoreAcceptHeader(true) 那么即使是返回JSON的XML API,一切都是JSON.
情况2:何时ignoreAcceptHeader(false)是默认值是XML.
我忘了提到我的API看起来像这样:
@RequestMapping(value = "/getXml", method = RequestMethod.GET)
public ResponseEntity<String> getXml( HttpServletRequest request)
throws JAXBException {
return returnXml();
}
Run Code Online (Sandbox Code Playgroud)
我在这里很丢失,我想要的只是默认(没有AcceptHeader)应该是JSON.(API将XML作为String返回)
当Accept Header:"Application/xml"被定义时,响应应该是XML.
任何建议都会有很大的帮助.
谢谢.
对我来说,添加
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
}
}
Run Code Online (Sandbox Code Playgroud)
解决了问题。
现在默认情况下,RestController如果Accept请求中没有标头,则所有 s 都会返回 JSON。此外,如果Accept: application/xml传递 header,则结果是 XML。
另外,值得一读:https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc
一般来说,如果你想获得 json 响应,你需要一个 jackson-databind 模块:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${json-jackson-version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
然后你必须MappingJackson2HttpMessageConverter在你的配置中定义一个:
@Configuration
@EnableWebMvc
public class WebAppMainConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
[..]
super.configureMessageConverters(converters);
}
[...]
}
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您可以实现自己的AbstractGenericHttpMessageConverter,以便您可以根据媒体类型在不同的具体转换器之间切换此转换器。
检查方法 AbstractGenericHttpMessageConverter#writeInternal(..)
| 归档时间: |
|
| 查看次数: |
5116 次 |
| 最近记录: |