Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTFUL webservice spring, XML in stead of JSON?

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?

like image 410
mikhail90 Avatar asked Sep 20 '13 15:09

mikhail90


2 Answers

Spring supports JSON by default, but to support XML as well, do these steps -

  1. In the class you plan to return as response, add xml annotations. for e.g.
    @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;
        }
    }
  1. Add produces and consumes to your @RequestMapping on the restful method like below, this helps in making sure what kind of responses and request you support, if you only want response as xml, only put produces = "application/xml".
@RequestMapping(value = "/api", method = RequestMethod.POST, consumes = {"application/xml", "application/json"}, produces = {"application/xml", "application/json"})

public

  1. Then, make sure you return the response object from your method call like below, you can add @ResponseBody just before return type but in my experience, my app worked fine without it.
public Response produceMessage(@PathVariable String topic, @RequestBody String message) {
    return new Response();
}
  1. Now, if you are supporting multiple produces types, then based on what client sent as the Accept in the HTTP request header, the spring restful service will return that type of response. If you only want to support xml, then only produce 'application/xml' and the response will always be xml.
like image 153
Vikram Gulia Avatar answered Sep 28 '22 07:09

Vikram Gulia


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:

  • Object annotated with JAXB
  • JAXB library existed in classpath
  • “mvc:annotation-driven” is enabled
  • Return method annotated with @ResponseBody

Follow this sample to know more:

http://www.mkyong.com/spring-mvc/spring-3-mvc-and-xml-example/

like image 40
Juned Ahsan Avatar answered Sep 28 '22 07:09

Juned Ahsan