alvinegro
alvinegro

Reputation: 81

Spring RestTemplate and XMLStream use with List of Objects

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> </employees>

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

Upvotes: 8

Views: 11593

Answers (4)

realPK
realPK

Reputation: 2961

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.

Upvotes: 0

sgrover
sgrover

Reputation: 37

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

Upvotes: 1

MaddHacker
MaddHacker

Reputation: 1128

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.

Upvotes: 16

Paul
Paul

Reputation: 20061

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

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

Upvotes: 0

Related Questions