在桌面应用程序中使用 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}]"
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to 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()
最佳答案
尝试使用数组:
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();
}
关于java - 在桌面应用程序中使用 RestTemplate 使用 Rest 服务时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6622287/