I am working on setting up REST API with Spring 4. The HTTP Message converters are present by default for JSON & XML. I try to setup two end-points, one for returning JSON & another for XML. The JSON object seems to be returned as expected but when i try to hit xml, i end up with 406 exception,
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
I have included the Maven dependencies for both JSON & XML. Below is the Snippet of pom.xml,
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jaxb-api.version}</version>
</dependency>
Below is the controller code,
@RestController
@RequestMapping(value="/employee")
public class HelloController {
@RequestMapping(method=RequestMethod.GET , produces="application/json",value="/hello.json")
public List<Employee> getEmployeeJson(){
Employee emp = new Employee();
emp.setId(1);
emp.setName("x");
Employee emp1 = new Employee();
emp1.setId(2);
emp1.setName("y");
List<Employee> res = new ArrayList<Employee>();
res.add(emp);
res.add(emp1);
return res;
}
@RequestMapping(method=RequestMethod.GET , produces="application/xml",value="/hello.xml")
public List<Employee> getEmployeeXml(){
Employee emp = new Employee();
emp.setId(1);
emp.setName("x");
Employee emp1 = new Employee();
emp1.setId(2);
emp1.setName("y");
List<Employee> res = new ArrayList<Employee>();
res.add(emp);
res.add(emp1);
return res;
}
}
Do share your thoughts on what am missing here
According to the documentation you should add jackson-dataformat-xml dependency to enable response body XML serialization. In case you are using Maven just add:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With