How does Spring know to convert return object to JSON and not XML or any other format?

Viewed 250

Consider the following:

@GetMapping("/accounts/{id}")
@ResponseBody
public Account handle() {
    return new Account("1", "sample");
}

There is no Accept header specified in the request, but still the response is by default converted to JSON when Spring Boot is used. The @ResponseBody annotation, in its documentation, doesn't mention anything about there being a conversion

4 Answers
By default, A controller return JSON on spring boot project. But If you want XML format then you can configure this on the pom.xml. For example, you can add this following dependency if you want to return XML data,

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

Spring uses Jackson/Json by default (by finding it in the classpath), but you can configure you're own:

@Configuration
public class MixInWebConfig extends WebMvcConfigurationSupport {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(customHttpMessageConverter());
    }
}

See HttpMessageConverter API

Spring-boot applications uses spring-boot-starter-web in dependencies of POM.xml. That particular dependency downloads fasterxmls jackson-datatype which is initialized when we use @springbootapplication.

In @requestMapping, You can add variables like Produces or Consumes Eg:

consumes = MediaType.APPLICATION_JSON_VALUE 
produces = MediaType.APPLICATION_JSON_VALUE
Related