经过之前的文章 spring-boot(一) web应用 发布后,有网友反馈说只返回对象,是如何达到让api返回json结果的,故在写一篇文章介绍下多种格式的响应输出配置.
本文介绍如何返回json和xml , 案例代码在 "spring-boot(二)数据库操作" 基础上改造
项目结构图:
-
pom增加xml的响应支持
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency>
-
HelloBean类增加xml注解支持
package hello.model; import java.util.Date; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * @author majinding888@foxmail.com * @date 2016-12-21 下午12:22:18 */ @XmlRootElement public class HelloBean { private Integer id; private String msg; private Date date; public HelloBean() { } public HelloBean(Integer id, String msg, Date date) { super(); this.id = id; this.msg = msg; this.date = date; } @XmlElement public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @XmlElement public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @XmlElement public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
-
在controller中配置xml和json的导航支持
@RequestMapping(value = "/hello/json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Object helloBean() { return new HelloBean(123,"你好",new Date()); } @RequestMapping(value = "/hello/xml", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public Object xml() { return new HelloBean(123,"你好",new Date()); }
到此为止已经配置完成, 启动主启动类, 浏览器访问
源代码参见附件: my-springboot-3.zip