简体   繁体   English

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. 我已经解决了其他类似问题,但对我来说没有任何效果。

All my API's return JSON as response by Default : 默认情况下,所有API都将JSON作为响应返回

Because of some XML API, i had to add jackson-xml 由于一些XML API,我不得不添加jackson-xml

    <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>

Now by default " Without accept header" All responses are XML . 现在默认情况下“ 没有接受标头”所有响应都是XML

I would like to have JSON as default Response format . 我想将JSON作为默认的响应格式

As stated in the doc here: 正如文档中所述:

https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

I implemented the following config : 我实现了以下配置:

@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);
    }

Case 1: if i make the ignoreAcceptHeader(true) then everything is JSON even the XML API returning JSON. 情况1:如果我使用ignoreAcceptHeader(true)那么即使返回JSON的XML API,一切都是JSON。

Case 2: when ignoreAcceptHeader(false) is then default is XML. 情况2:ignoreAcceptHeader(false)为则默认为XML。

I forget to mention my API's look like this: 我忘了提到我的API看起来像这样:

@RequestMapping(value = "/getXml", method = RequestMethod.GET)
public ResponseEntity<String> getXml( HttpServletRequest request)
        throws JAXBException {
    return returnXml();
}

I am quite lost here, All i want is Default(Without AcceptHeader) should be JSON. 我在这里很丢失,我想要的只是默认(没有AcceptHeader)应该是JSON。 (API returns XML as String) (API将XML作为String返回)

And when Accept Header : "Application/xml" is defined then response should be XML. 当Accept Header:“Application / xml”被定义时,响应应该是XML。

Any advice would be of great help. 任何建议都会有很大的帮助。

Thanks. 谢谢。

In general if you want to get json response you need an jackson-databind module: 一般来说,如果你想获得json响应,你需要一个jackson-databind模块:

<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
    <version>${json-jackson-version}</version> 
</dependency> 

and then you have to define a MappingJackson2HttpMessageConverter in your configuration: 然后你必须在配置中定义一个MappingJackson2HttpMessageConverter

@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,以便根据介质类型在不同的具体转换器之间切换此转换器。

Check the method AbstractGenericHttpMessageConverter#writeInternal(..) 检查方法AbstractGenericHttpMessageConverter#writeInternal(..)

As you have set ignoreAcceptHeader to true and favorPathExtension to false, spring will rely on other alternatives for content negotiations. 由于您已将ignoreAcceptHeader设置为true并将favorPathExtension设置为false,因此spring将依赖其他替代方法进行内容协商。 Means it will look URL parameter which you have configured XML and JSON 意味着它将显示您已配置XML和JSON的URL参数

so as @stan pointed /getXml?mediaType=xml will should return xml response else it will default to json(defaultContentType(MediaType.APPLICATION_JSON)) 所以@stan指向/getXml?mediaType=xml将返回xml响应,否则它将默认为json(defaultContentType(MediaType.APPLICATION_JSON))

For me, adding 对我来说,补充一下

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
    }

}

solved the problem. 解决了这个问题。

Now by default all RestController s return JSON, if no Accept header in the request. 现在默认情况下,如果请求中没有Accept标头,则所有RestController返回JSON。 Also if Accept: application/xml header is passed, then result is XML. 此外,如果传递Accept: application/xml标头,则结果为XML。

Also, worth reading: https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc 另外,值得一读: https//spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM