jgr*_*jgr 7 xml rest spring jaxb spring-boot
我使用Spring Boot 1.2.5创建了一个简单的REST Web服务,它适用于JSON,但我不能让这个工作返回XML.
这是我的控制器:
@RestController
..
@RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseStatus(HttpStatus.OK)
public List<Activity> getAllActivities() {
return activityRepository.findAllActivities();
}
Run Code Online (Sandbox Code Playgroud)
当我调用它时,Accept: application/json一切正常,但当我尝试时,application/xml我得到一些带有406错误和消息的HTML:
The resource identified by this request is only capable of generating responses
with characteristics not acceptable according to the request "accept" headers.
Run Code Online (Sandbox Code Playgroud)
我的模型对象:
@XmlRootElement
public class Activity {
private Long id;
private String description;
private int duration;
private User user;
//getters & setters...
}
@XmlRootElement
public class User {
private String name;
private String id;
//getters&setters...
}
Run Code Online (Sandbox Code Playgroud)
我的pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Run Code Online (Sandbox Code Playgroud)
我的pom.xml中是否需要一些额外的jar才能使其正常工作?我尝试添加jaxb-api或jax-impl,但它没有帮助.
jgr*_*jgr 19
要在不使用Jersey的情况下在Spring Boot中使用它,我们需要添加此依赖项:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
输出会有点难看,但它的工作原理:
<ArrayList
xmlns="">
<item>
<id/>
<description>Swimming</description>
<duration>55</duration>
<user/>
</item>
<item>
<id/>
<description>Cycling</description>
<duration>120</duration>
<user/>
</item>
</ArrayList>
Run Code Online (Sandbox Code Playgroud)
这是一个很好的教程:http: //www.javacodegeeks.com/2015/04/jax-rs-2-x-vs-spring-mvc-returning-an-xml-representation-of-a-list-of-objects html的
| 归档时间: |
|
| 查看次数: |
20581 次 |
| 最近记录: |