【问题标题】:Issue When Consume Rest Service with RestTemplate in Desktop App在桌面应用程序中使用 RestTemplate 使用 Rest 服务时的问题
【发布时间】:2011-10-01 03:01:12
【问题描述】:

在桌面应用程序中使用 RestTemplate 使用 Rest 服务时出现问题,而在 Web 应用程序中使用时问题未出现。

这是调试日志

15:30:40.448 [main] DEBUG o.s.web.client.RestTemplate - Reading [java.util.List] as "application/json" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@98adae2]
15:30:40.452 [main] DEBUG httpclient.wire.content - << "[{"name":"Indonesia","id":1},{"name":"AlaySia","id":2},{"name":"Autraliya","id":3}]"

线程“main”java.lang.ClassCastException 中的异常:java.util.LinkedHashMap 无法转换为 com.mgm.domain.Country

这是我使用的代码。

 String url = "http://localhost:8080/mgm/country";
    List<MediaType> mediaTypes = new ArrayList<MediaType>();
    mediaTypes.add(MediaType.APPLICATION_JSON);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(mediaTypes);
    HttpEntity<Country> httpEntity = new HttpEntity<Country>(null, headers);
    try {
        ResponseEntity<List> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, List.class);
        List<Country> countries = responseEntity.getBody();
        System.out.println(countries.get(0).getName());

    } catch (RestClientException exception) {
        exception.printStackTrace();
    }

当我将上面的代码放在网络应用程序中时,它不会出错。我使用 Spring Rest MVC 提供 JSON 并使用 RestTemplate 使用它。

我认为 Jackson 将 java.util.LinkedHashMap 转换为 Country 时存在问题。似乎countries.get(0) 实际上有LinkedHashMap 类型而不是Country 并且当我调用Country 方法之一时会出现问题,例如.getName()

【问题讨论】:

  • to all:需要注意的一点,RestTemplate 位于 spring-web jar 中。所以它是 Spring Web 项目的一部分。

标签: java spring spring-mvc resttemplate


【解决方案1】:

尝试使用数组代替:

String url = "http://localhost:8080/mgm/country";
List<MediaType> mediaTypes = new ArrayList<MediaType>();
mediaTypes.add(MediaType.APPLICATION_JSON);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(mediaTypes);
HttpEntity<Country> httpEntity = new HttpEntity<Country>(null, headers);
try {
    ResponseEntity<Country[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Country[].class);
    Country[] countries = responseEntity.getBody();
    System.out.println(countries[0].getName());

} catch (RestClientException exception) {
    exception.printStackTrace();
}

【讨论】:

  • +1。遇到同样的问题,经过一些研究,我发现了你的解决方案,来到这里回答它,看到你打败了我:-) 原因显然是你不能将 List&lt;Country&gt;.class 传递给 exchange() 方法,所以当它解组时,它无法知道List 输入的类型(Country)。数组可以作为Class 对象传递,因此可以将类型信息传递给底层的解组器。
  • 是的,这是由于 Java 的泛型机制中的类型擦除效应。更多可以在这里找到:stackoverflow.com/questions/339699/… 只需加上我的 2 美分
猜你喜欢
  • 2011-01-04
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 2016-10-07
  • 2019-01-26
  • 1970-01-01
相关资源
最近更新 更多