gpt4 book ai didi

xml - 支持 XML 的 Spring Boot REST

转载 作者:数据小太阳 更新时间:2023-10-29 01:46:20 26 4
gpt4 key购买 nike

我使用 Spring Boot 1.2.5 制作了一个简单的 REST 网络服务,它适用于 JSON,但我无法让这项工作返回 XML。

这是我的 Controller :

@RestController
..
@RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseStatus(HttpStatus.OK)
public List<Activity> getAllActivities() {
return activityRepository.findAllActivities();
}

当我使用 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.

我的模型对象:

@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...
}

我的 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>

我的 pom.xml 中是否需要一些额外的 jar 才能完成这项工作?我尝试添加 jaxb-api 或 jax-impl,但没有帮助。

最佳答案

要在不使用 Jersey 的情况下在 Spring Boot 中实现此功能,我们需要添加以下依赖项:

<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>

输出会有点难看,但它有效:

<ArrayList 
xmlns="">
<item>
<id/>
<description>Swimming</description>
<duration>55</duration>
<user/>
</item>
<item>
<id/>
<description>Cycling</description>
<duration>120</duration>
<user/>
</item>
</ArrayList>

这是一个很好的教程: http://www.javacodegeeks.com/2015/04/jax-rs-2-x-vs-spring-mvc-returning-an-xml-representation-of-a-list-of-objects.html

关于xml - 支持 XML 的 Spring Boot REST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32654291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com