Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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**
like image 922
alvinegro Avatar asked Apr 15 '11 19:04

alvinegro


People also ask

Why RestTemplate is deprecated?

RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof. First, we create a Spring Boot project with the spring-boot-starter-web dependency.

What is difference between getForObject and getForEntity?

For example, the method getForObject() will perform a GET and return an object. getForEntity() : executes a GET request and returns an object of ResponseEntity class that contains both the status code and the resource as an object. getForObject() : similar to getForEntity() , but returns the resource directly.

How do you pass multiple parameters in RestTemplate?

Query parameters are passed after the URL string by appending a question mark followed by the parameter name , then equal to (“=”) sign and then the parameter value. Multiple parameters are separated by “&” symbol.


1 Answers

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.

like image 148
MaddHacker Avatar answered Nov 03 '22 14:11

MaddHacker