I am trying to return an object as XML in spring, exactly like this guide: http://spring.io/guides/gs/rest-service/
Except that I want the object to return as xml instead of JSON.
Anyone know how I can do that? Does Spring have any dependancies that can do this as easily for XML? Or, do I need to use a marshaller and then return the xml file some other way?
Spring supports JSON by default, but to support XML as well, do these steps -
    @XmlRootElement(name = "response")
    @XmlAccessorType(XmlAccessType.FIELD) => this is important, don't miss it.
    public class Response {
        @XmlElement
        private Long status;
        @XmlElement
        private String error;
        public Long getStatus() {
            return status;
        }
        public void setStatus(Long status) {
            this.status = status;
        }
        public String getError() {
            return error;
        }
        public void setError(String error) {
            this.error = error;
        }
    }
@RequestMapping(value = "/api", method = RequestMethod.POST, consumes = {"application/xml", "application/json"}, produces = {"application/xml", "application/json"})
public
public Response produceMessage(@PathVariable String topic, @RequestBody String message) {
    return new Response();
}
If you use JAXB annotations in your bean to define @XmlRootElement and @XmlElement then it should marshall it xml. Spring will marshall the bean to xml when it sees:
Follow this sample to know more:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-xml-example/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With