spring-boot(三)响应返回json和xml
spring-boot
420
马晶晶
: 2016-12-22 15:14:25

经过之前的文章 spring-boot(一) web应用 发布后,有网友反馈说只返回对象,是如何达到让api返回json结果的,故在写一篇文章介绍下多种格式的响应输出配置.

本文介绍如何返回json和xml , 案例代码在 “spring-boot(二)数据库操作” 基础上改造

项目结构图:
QQ截图20161222151507.png

  1. pom增加xml的响应支持

    1. <dependency>
    2. <groupId>com.fasterxml.jackson.dataformat</groupId>
    3. <artifactId>jackson-dataformat-xml</artifactId>
    4. </dependency>
  2. HelloBean类增加xml注解支持

    1. package hello.model;
    2. import java.util.Date;
    3. import javax.xml.bind.annotation.XmlElement;
    4. import javax.xml.bind.annotation.XmlRootElement;
    5. /**
    6. * @author majinding888@foxmail.com
    7. * @date 2016-12-21 下午12:22:18
    8. */
    9. @XmlRootElement
    10. public class HelloBean {
    11. private Integer id;
    12. private String msg;
    13. private Date date;
    14. public HelloBean() {
    15. }
    16. public HelloBean(Integer id, String msg, Date date) {
    17. super();
    18. this.id = id;
    19. this.msg = msg;
    20. this.date = date;
    21. }
    22. @XmlElement
    23. public Integer getId() {
    24. return id;
    25. }
    26. public void setId(Integer id) {
    27. this.id = id;
    28. }
    29. @XmlElement
    30. public String getMsg() {
    31. return msg;
    32. }
    33. public void setMsg(String msg) {
    34. this.msg = msg;
    35. }
    36. @XmlElement
    37. public Date getDate() {
    38. return date;
    39. }
    40. public void setDate(Date date) {
    41. this.date = date;
    42. }
    43. }
  3. 在controller中配置xml和json的导航支持

    1. @RequestMapping(value = "/hello/json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    2. @ResponseBody
    3. public Object helloBean() {
    4. return new HelloBean(123,"你好",new Date());
    5. }
    6. @RequestMapping(value = "/hello/xml", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
    7. @ResponseBody
    8. public Object xml() {
    9. return new HelloBean(123,"你好",new Date());
    10. }

到此为止已经配置完成, 启动主启动类, 浏览器访问
QQ截图20161222151103.png

QQ截图20161222151129.png


源代码参见附件: my-springboot-3.zip