resttemplate是一個(gè)很方便的HTTP客戶(hù)端坛善,但是當(dāng)返回的數(shù)據(jù)類(lèi)型是泛型時(shí)會(huì)報(bào)錯(cuò)
//一般用法婶溯,通過(guò)postForObject獲取結(jié)果
REST_TEMPLATE.postForObject(supplier.getApi(),param,Result.class)
//Result.java
public class Result<T> {
private int code;
private List<T> data;
...
}
//報(bào)錯(cuò)
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx
原因:
postForObject無(wú)法知道具體的實(shí)例化類(lèi)型硅瞧,解析為了LinkedHashMap
解決方法蓄氧,使用exchange方法替代:
Map<String,Object> param = new HashedMap();
param.put("key","value");//傳入?yún)?shù)
parameterizedTypeReference =
new ParameterizedTypeReference<Result<XXX>>(){};
//XXX為實(shí)例化的類(lèi)型
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(new Gson().toJson(param),headers);
ResponseEntity<YunResult<Instance>> result =
REST_TEMPLATE.exchange(url, HttpMethod.POST, entity,
parameterizedTypeReference);