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,请执行以下步骤 -
@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)
@RequestMapping(value = "/api", method = RequestMethod.POST, consumes = {"application/xml", "application/json"}, produces = {"application/xml", "application/json"})
Run Code Online (Sandbox Code Playgroud)
上市
public Response produceMessage(@PathVariable String topic, @RequestBody String message) {
return new Response();
}
Run Code Online (Sandbox Code Playgroud)
如果你在bean中使用JAXB注释来定义它@XmlRootElement,@XmlElement那么它应该将它编组为xml.Spring会在看到bean时将bean编组为xml:
请按照此示例了解更多信息:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-xml-example/
| 归档时间: |
|
| 查看次数: |
12063 次 |
| 最近记录: |