RESTFUL web service spring,XML而不是JSON?

Posted

技术标签:

【中文标题】RESTFUL web service spring,XML而不是JSON?【英文标题】:RESTFUL webservice spring, XML in stead of JSON? 【发布时间】:2013-09-26 01:52:15 【问题描述】:

我试图在春季以 XML 形式返回一个对象,就像本指南一样:http://spring.io/guides/gs/rest-service/

除了我希望对象返回为 xml 而不是 JSON。

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

【问题讨论】:

它不工作***.com/questions/38026928/… 【参考方案1】:

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

    在您计划作为响应返回的类中,添加 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;
        
    
    在下面的 restful 方法上将生产和消费添加到您的 @RequestMapping,这有助于确保您支持什么样的响应和请求,如果您只想将响应作为 xml,只放生产= "应用程序/xml"。
@RequestMapping(value = "/api", method = RequestMethod.POST, consumes = "application/xml", "application/json", produces = "application/xml", "application/json")

公开

    然后,确保从您的方法调用中返回响应对象,如下所示,您可以在返回类型之前添加@ResponseBody,但根据我的经验,没有它我的应用程序运行良好。
public Response produceMessage(@PathVariable String topic, @RequestBody String message) 
    return new Response();

    现在,如果您支持多种生产类型,则根据客户端在 HTTP 请求标头中作为 Accept 发送的内容,spring restful 服务将返回该类型的响应。如果你只想支持 xml,那么只生成 'application/xml' 并且响应总是 xml。

【讨论】:

如果我对 Json 和 Xml 使用相同的实体,我该怎么做? 据我所知,Spring 默认支持 JSON,因此您可以使用相同的实体,只需按照上面的建议使用两个 xml 注释对其进行注释。您只需要在请求映射中使用produce = "application/xml", "application/json" 来支持您的实体的两种或任何一种类型。现在如果客户端请求 JSON 内容类型,响应将以 JSON 格式发送。【参考方案2】:

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

用 JAXB 注释的对象 类路径中存在 JAXB 库 “mvc:annotation-driven”已启用 使用@ResponseBody 注释的返回方法

关注此示例以了解更多信息:

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

【讨论】:

谢谢!这是完美的。 @mikhail90 如果有用于 JSON 的 HttpMessageConverter 设置,则 @ResponseBody 本身是不够的。基本上,Spring 将使用它找到的第一个可以执行转换的。一个安全的方法是用MediaType.APPLICATION_XML返回ResponseEntity

以上是关于RESTFUL web service spring,XML而不是JSON?的主要内容,如果未能解决你的问题,请参考以下文章

Web Service简介(RESTful Web Services 第一章笔记)

转Spring 4.x实现Restful web service

zzWCF实现RESTFul Web Service

RESTful Web Services简单介绍

Web Service学习之九:Restful WebService

RESTful Web Service实战 小结1