jgr jgr - 2 months ago 14
reST (reStructuredText) Question

Spring Boot REST with XML Support

I made simple rest webservice with Spring Boot 1.2.5 and it works fine for json but i cant make this work to return xml.

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


When i call it with Accept: application/json everything works, but when i try with application/xml i get some HTML with 406 Error and message:

The resource identified by this request is only capable of generating responses
with characteristics not acceptable according to the request "accept" headers.


My model objects:

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





My 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>


Do i need some additional jars in my pom.xml to make this work? I tried adding jaxb-api or jax-impl but it didnt help.

jgr jgr
Answer

To make this work in Spring Boot without using Jersey we need to add this dependency:

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

The output will be a bit ugly but it works:

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

Here is nice tutorial: http://www.javacodegeeks.com/2015/04/jax-rs-2-x-vs-spring-mvc-returning-an-xml-representation-of-a-list-of-objects.html

Comments