在桌面应用程序中使用RestTemplate消费Rest Service时出现的问题


问题内容

在桌面应用程序中使用带有RestTemplate的Consrest Rest Service时遇到问题,而在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}]"

线程“主”中的异常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();
    }

当我将其放在Web应用程序中时,上面的代码不会给出错误。我使用Spring Rest MVC提供JSON并将其与RestTemplate一起使用。

我觉得这是一个问题,当杰克逊转换java.util.LinkedHashMapCountry。它似乎countries.get(0)实际上没有LinkedHashMap类型,Country并且当我调用Country方法之一时会出现问题.getName()


问题答案:

尝试改用数组:

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