I am trying to use Spring RestTemplate
to retrieve a List of Employee records, such as:
public List<Employee> getEmployeesByFirstName(String firstName) {
return restTemplate.getForObject(employeeServiceUrl + "/firstname/{firstName}", List.class, firstName);
}
Problem is that web services (being called), returns the following XML format:
<employees> <employee> .... </employee> <employee> .... </employee> </employee开发者_如何学Pythons>
So when executing method above, I get following error:
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**
You're probably looking for something like this:
public List<Employee> getEmployeeList() {
Employee[] list = restTemplate.getForObject("<some URI>", Employee[].class);
return Arrays.asList(list);
}
That should marshall correctly, using the auto-marshalling.
Make sure that the Marshaller and Unmarshaller that you are passing in the parameter to RestTemplate constructor has defaultImplementation set.
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);
I had a similar problem and solved it as in this example:
http://blog.springsource.com/2009/03/27/rest-in-spring-3-resttemplate/
I was trying to use RestTemplate as a RestClient and following code works for fetching 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 your Domain objects are properly annotated and XMLStream jar in classpath. It has to work with above condition being satisfied.
精彩评论