Spring Using RestTemplate and XMLStream with a list of objects

I am trying to use Spring RestTemplate to retrieve employee list entries, for example:

 public List<Employee> getEmployeesByFirstName(String firstName) { return restTemplate.getForObject(employeeServiceUrl + "/firstname/{firstName}", List.class, firstName); } 

The problem is that web services (called) return the following XML format:

<employees> <& employee GT; .... </employee> <& employee GT; .... </employee> <& / employees GT;

Therefore, when executing the above method, the following error occurs:

 org.springframework.http.converter.HttpMessageNotReadableException: Could not read [interface java.util.List]; nested exception is org.springframework.oxm.UnmarshallingFailureException: XStream unmarshalling exception; nested exception is com.thoughtworks.xstream.mapper.CannotResolveClassException: **employees : employees** 
+7
source share
4 answers

You are probably looking for something like this:

 public List<Employee> getEmployeeList() { Employee[] list = restTemplate.getForObject("<some URI>", Employee[].class); return Arrays.asList(list); } 

This should marshall correctly using automatic sorting.

+16
source

Make sure that the Marshaller and Unmarshaller that you pass in the RestTemplate constructor parameter have a defaultImplementation parameter.

Example:

 XStreamMarshaller marshaller = new XStreamMarshaller(); marshaller.getXStream().addDefaultImplementation(ArrayList.class,List.class); XStreamMarshaller unmarshaller = new XStreamMarshaller(); unmarshaller.getXStream().addDefaultImplementation(ArrayList.class,List.class); RestTemplate template = new RestTemplate(marshaller, unmarshaller); 
+1
source

I had a similar problem and solved it, as in this example:

http://blog.springsource.com/2009/03/27/rest-in-spring-3-resttemplate/

0
source

I tried using RestTemplate as a RestClient, and the following code works to retrieve the list:

 public void testFindAllEmployees() { Employee[] list = restTemplate.getForObject(REST_SERVICE_URL, Employee[].class); List<Employee> elist = Arrays.asList(list); for(Employee e : elist){ Assert.assertNotNull(e); } } 

Make sure that the domain objects are properly annotated and that the XMLStream jar is in the classpath. It must work in compliance with the above conditions.

0
source

All Articles