Spring mvc : Changing default Response format from xml to json

后端 未结 3 788
粉色の甜心
粉色の甜心 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:08

    In general if you want to get json response you need an jackson-databind module:

     
        com.fasterxml.jackson.core 
        jackson-databind 
        ${json-jackson-version} 
     
    

    and then you have to define a MappingJackson2HttpMessageConverter in your configuration:

    @Configuration
    @EnableWebMvc
    public class WebAppMainConfiguration extends WebMvcConfigurerAdapter {
    
        @Override 
        public void configureMessageConverters(List> 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(..)

提交回复
热议问题