Spring mvc : Changing default Response format from xml to json

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))


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


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(..)