In my previous post I talked about how to support both JSON and XML in a Spring MVC web service. The observant reader might have noticed that if a request was made with an Accept header with neither
The code will log the received data and you can see that it is in XML format. The reason for this is how the message converters are added by default. Go check out the Spring source code if you want to know the details.
Now, if you rather want JSON to be the default format then changing the behavior of our web service is simply a matter of defining our own order for the message converters and make sure the JSON converter comes before the Jaxb converter.
application/json
nor application/xml
specified then the data was returned in XML. The integration test in the example code used to illustrate this looked like this:@Test public void getUserWithUnsupportedAccept() throws Exception { RestTemplate restTemplate = createStringRestTemplate(); String user = restTemplate.getForObject(new URI(baseUrl + "/123"), String.class); logger.debug("Received data as: {}", user); }
The code will log the received data and you can see that it is in XML format. The reason for this is how the message converters are added by default. Go check out the Spring source code if you want to know the details.
Now, if you rather want JSON to be the default format then changing the behavior of our web service is simply a matter of defining our own order for the message converters and make sure the JSON converter comes before the Jaxb converter.