71.2 编写XML REST服务

如果classpath下存在Jackson XML扩展(jackson-dataformat-xml),它会被用来渲染XML响应,示例和JSON的非常相似。想要使用它,只需为你的项目添加以下依赖:

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.dataformat</groupId>
  3. <artifactId>jackson-dataformat-xml</artifactId>
  4. </dependency>

你可能还需要添加Woodstox的依赖,它比JDK提供的默认StAX实现快很多,并且支持良好的格式化输出,提高了namespace处理能力:

  1. <dependency>
  2. <groupId>org.codehaus.woodstox</groupId>
  3. <artifactId>woodstox-core-asl</artifactId>
  4. </dependency>

如果Jackson的XML扩展不可用,Spring Boot将使用JAXB(JDK默认提供),不过MyThing需要注解@XmlRootElement

  1. @XmlRootElement
  2. public class MyThing {
  3. private String name;
  4. // .. getters and setters
  5. }

想要服务器渲染XML而不是JSON,你可能需要发送一个Accept: text/xml头部(或使用浏览器)。