Spring MVC:将默认响应格式从xml更改为json [英] Spring mvc : Changing default Response format from xml to json
问题描述
我经历了其他类似的问题,但对我没有任何帮助.
I have gone through other similar asked questions but nothing worked for me.
我所有 API的返回JSON 作为响应,默认情况下:
由于某些XML API,我不得不添加jackson-xml
Because of some XML API, i had to add jackson-xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
现在默认为"没有接受标头".所有响应均为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);
}
案例1:,如果我输入ignoreAcceptHeader(true)
,则所有内容都是JSON,甚至XML API返回JSON.
Case 1: if i make the ignoreAcceptHeader(true)
then everything is JSON even the XML API returning JSON.
情况2:,当ignoreAcceptHeader(false)
为默认值时为XML.
Case 2: when ignoreAcceptHeader(false)
is then default is XML.
我忘了提及我的API的样子:
I forget to mention my API's look like this:
@RequestMapping(value = "/getXml", method = RequestMethod.GET)
public ResponseEntity<String> getXml( HttpServletRequest request)
throws JAXBException {
return returnXml();
}
我在这里很迷路,我想要的只是Default(不带AcceptHeader)应该是JSON. (API以字符串形式返回XML)
I am quite lost here, All i want is Default(Without AcceptHeader) should be JSON. (API returns XML as String)
并且当接受标头:定义了"Application/xml"时,响应应该是XML.
And when Accept Header : "Application/xml" is defined then response should be XML.
任何建议都会有很大帮助.
Any advice would be of great help.
谢谢.
推荐答案
通常,如果要获取json响应,则需要一个jackson-databind模块:
In general if you want to get json response you need an jackson-databind module:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${json-jackson-version}</version>
</dependency>
,然后必须在配置中定义MappingJackson2HttpMessageConverter
:
and then you have to define a MappingJackson2HttpMessageConverter
in your configuration:
@Configuration
@EnableWebMvc
public class WebAppMainConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
[..]
super.configureMessageConverters(converters);
}
[...]
}
In your case, you can implement your own AbstractGenericHttpMessageConverter so you can switch in this converter between different concrete converters depending on media type.
检查方法AbstractGenericHttpMessageConverter#writeInternal(..)
这篇关于Spring MVC:将默认响应格式从xml更改为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!