【问题标题】:Spring RestTemplate and XMLStream use with List of ObjectsSpring RestTemplate 和 XMLStream 与对象列表一起使用
【发布时间】:2011-04-15 19:49:13
【问题描述】:

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

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

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

.... 员工> .... 员工> 员工>

所以在执行上面的方法时,我得到以下错误:

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

【问题讨论】:

  • 我确实将属性“aliases”设置为包含一组值(如“employees”)和我们想要的结果类“org....Employees”的映射。希望能有所帮助。

标签: spring xstream resttemplate


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    确保您在参数中传递给 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);
    

    【讨论】:

      【解决方案3】:

      我遇到了类似的问题,并像这个例子一样解决了它:

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

      【讨论】:

        【解决方案4】:

        我试图将 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);
            }
        }
        

        确保您的域对象在类路径中正确注释和 XMLStream jar。它必须在满足上述条件的情况下工作。

        【讨论】:

          猜你喜欢
          • 2012-05-06
          • 2016-03-18
          • 2019-04-24
          • 2013-12-23
          • 1970-01-01
          • 1970-01-01
          • 2012-01-19
          • 2020-09-10
          • 1970-01-01
          相关资源
          最近更新 更多