spring_reference/IX. ‘How-to’ guides/65.2. Write an XML REST ser...

26 lines
1.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### 65.2. 编写一个XML REST服务
如果classpath下存在Jackson XML扩展jackson-dataformat-xml它会被用来渲染XML响应示例和JSON的非常相似。想要使用它只需为你的项目添加以下的依赖
```xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
```
你可能也想添加对Woodstox的依赖。它比JDK提供的默认Stax实现快很多并且支持良好的格式化输出提高了namespace处理能力
```xml
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
</dependency>
```
如果Jackson的XML扩展不可用Spring Boot将使用JAXBJDK默认提供不过你需要为MyThing添加额外的注解`@XmlRootElement`
```java
@XmlRootElement
public class MyThing {
private String name;
// .. getters and setters
}
```
想要服务器渲染XML而不是JSON你可能需要发送一个`Accept: text/xml`头部(或使用浏览器)。