小编典典

具有XML支持的Spring Boot REST

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();
}

当我调用它时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,但没有帮助。


阅读 341

收藏
2020-05-30

共1个答案

小编典典

为了在不使用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>
2020-05-30