RESTFUL webservice spring,XML代替JSON?

mik*_*l90 5 java xml rest spring json

我试图在春天将对象作为XML返回,就像本指南一样: http //spring.io/guides/gs/rest-service/

除了我希望对象以xml而不是JSON的形式返回.

谁知道我怎么能这样做?Spring是否有任何依赖可以轻松地为XML做到这一点?或者,我是否需要使用marshaller然后以其他方式返回xml文件?

Vik*_*lia 10

Spring默认支持JSON,但为了支持XML,请执行以下步骤 -

  1. 在您计划作为响应返回的类中,添加xml注释.例如
    @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;
        }
    }
Run Code Online (Sandbox Code Playgroud)
  1. 在下面的restful方法中添加产生和消耗你的@RequestMapping,这有助于确定你支持哪种响应和请求,如果你只想要响应为xml,只需要put ="application/xml".
@RequestMapping(value = "/api", method = RequestMethod.POST, consumes = {"application/xml", "application/json"}, produces = {"application/xml", "application/json"})
Run Code Online (Sandbox Code Playgroud)

上市

  1. 然后,确保从方法调用中返回响应对象,如下所示,您可以在返回类型之前添加@ResponseBody,但根据我的经验,我的应用程序在没有它的情况下工作正常.
public Response produceMessage(@PathVariable String topic, @RequestBody String message) {
    return new Response();
}
Run Code Online (Sandbox Code Playgroud)
  1. 现在,如果您支持多种产品类型,那么基于客户端在HTTP请求标头中作为Accept发送的内容,spring restful服务将返回该类型的响应.如果您只想支持xml,那么只生成'application/xml',响应将始终为xml.


Jun*_*san 7

如果你在bean中使用JAXB注释来定义它@XmlRootElement,@XmlElement那么它应该将它编组为xml.Spring会在看到bean时将bean编组为xml:

  • 用JAXB注释的对象
  • JAXB库存在于classpath中
  • "mvc:annotation-driven"已启用
  • 使用@ResponseBody注释的返回方法

请按照此示例了解更多信息:

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