Spring mvc : Changing default Response format from xml to json

后端 未结 3 755
粉色の甜心
粉色の甜心 2021-01-17 10:07

I have gone through other similar asked questions but nothing worked for me.

All my API\'s return JSON as response by Default:

相关标签:
3条回答
  • 2021-01-17 11:05

    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 RestControllers return JSON, if no Accept header in the request. Also if Accept: application/xml header is passed, then result is XML.

    Also, worth reading: https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

    0 讨论(0)
  • 2021-01-17 11:08

    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> 
    

    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.

    Check the method AbstractGenericHttpMessageConverter#writeInternal(..)

    0 讨论(0)
  • 2021-01-17 11:09

    As you have set ignoreAcceptHeader to true and favorPathExtension to false, spring will rely on other alternatives for content negotiations. Means it will look URL parameter which you have configured XML and JSON

    so as @stan pointed /getXml?mediaType=xml will should return xml response else it will default to json(defaultContentType(MediaType.APPLICATION_JSON))

    0 讨论(0)
提交回复
热议问题