Spring RestTemplate和XMLStream与对象列表一起使用

时间:2011-04-15 19:49:13

标签: spring xstream resttemplate

我正在尝试使用Spring RestTemplate来检索员工记录列表,例如:

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

问题是Web服务(被调用)返回以下XML格式:

  

&LT;员工&GT; &LT;雇员&GT; ....&lt; / employee&gt;   &LT;雇员&GT; ....&lt; / employee&gt; &LT; /雇员&GT;

因此,当执行上述方法时,我收到以下错误:

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

4 个答案:

答案 0 :(得分:16)

你可能正在寻找这样的东西:

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

应该使用自动编组正确编组。

答案 1 :(得分:1)

确保您将参数传递给RestTemplate构造函数的Marshaller和Unmarshaller设置了defaultImplementation。

示例:

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

答案 2 :(得分:0)

我遇到了类似的问题,并在此示例中解决了这个问题:

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

答案 3 :(得分:0)

我试图将RestTemplate用作RestClient,以下代码可用于获取列表:

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

确保在classpath中正确注释了Domain对象和XMLStream jar。它必须满足上述条件。