java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx.xxx

阅读更多

 

使用Spring的RestTemplate访问REST的WEB服务的时候,发现如下的异常:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to

 原来的代码如下:

List myModelClass=(List) restTemplate.postForObject(url,mvm,List.class);

 问题原因:postForObject无法知道具体的实例化类型,解析为了LinkedHashMap。

解决方法,使用exchange方法,并且使用 ParameterizedTypeReference 指定参数引用类型,帮助程序了解需要反序列化的类型信息。

ParameterizedTypeReference> typeRef = new ParameterizedTypeReference>() {};
ResponseEntity> responseEntity =
                restTemplate.exchange(url, HttpMethod.POST, request, typeRef);
List result = responseEntity.getBody();  

 API描述:

 ResponseEntity org.springframework.web.client.RestOperations.exchange(String url, HttpMethod method, HttpEntity requestEntity, ParameterizedTypeReference responseType, Object... uriVariables) throws RestClientException

Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as ResponseEntity. The given ParameterizedTypeReference is used to pass generic type information:

 ParameterizedTypeReference> myBean = new ParameterizedTypeReference>() {};
 ResponseEntity> response = template.exchange("http://example.com",HttpMethod.GET, null, myBean);
 
Type Parameters:

Parameters:
url the URL
method the HTTP method (GET, POST, etc)
requestEntity the entity (headers and/or body) to write to the request (may be null)
responseType the type of the return value
uriVariables the variables to expand in the template
Returns:
the response as entity
Throws:
RestClientException
Since:
3.2

 

 

你可能感兴趣的:(java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx.xxx)