STORY:
So you are learning Spring Boot and you learn quickly that in order to get json response you simply need to write method in Controller with @RestController annotation (as shown on orange example in the end of this post).
However, if you try produce xml output instead (as shown on blue example) ,then ...unfortunately .. you will that Spring will display error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Oct 11 11:23:37 GMT 2016
There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation
And in logs you will see:
2016-12-13 11:23:37.760 WARN 7456 --- [io-16801-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
For example for Gradle:
compile('com.fasterxml.jackson.dataformat:jackson-dataformat-xml')
refresh your dependencies and re-run application and it should works :)
This an example:
Source: http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-write-an-xml-rest-service@RestController
public class JsonController {
private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(JsonController.class);
@GetMapping("/json")
public CuteDomainObject getCuteDomainObjectAsJson() {
CuteDomainObject cuteDomainObject = new CuteDomainObject("Name", new Random().nextInt(32));
LOGGER.info("Getting Cute Domain Object with data: " + cuteDomainObject.toString());
return cuteDomainObject;
}
@GetMapping(value = "/xml", produces = { "application/xml", "text/xml"})
public CuteDomainObject getCuteDomainObjectAsXml() {
CuteDomainObject cuteDomainObject = new CuteDomainObject("Name", new Random().nextInt(32));
LOGGER.info("Getting Cute Domain Object with data: " + cuteDomainObject.toString());
return cuteDomainObject;
}
}
No comments:
Post a Comment