resttemplate是一个很方便的HTTP客户端,但是当返回的数据类型是泛型时会报错
//一般用法,通过postForObject获取结果
REST_TEMPLATE.postForObject(supplier.getApi(),param,Result.class)
//Result.java
public class Result<T> {
private int code;
private List<T> data;
...
}
//报错
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx
原因:
postForObject无法知道具体的实例化类型,解析为了LinkedHashMap
解决方法,使用exchange方法替代:
Map<String,Object> param = new HashedMap();
param.put("key","value");//传入参数
parameterizedTypeReference =
new ParameterizedTypeReference<Result<XXX>>(){};
//XXX为实例化的类型
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);