spring resttemplate泛型

resttemplate是一个很方便的HTTP客户端,但是当返回的数据类型是泛型时会报错

//一般用法,通过postForObject获取结果
REST_TEMPLATE.postForObject(supplier.getApi(),param,Result.class)
//Result.java
public class Result {
    private int code;
    private List data;
...
}
//报错
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx

原因:
postForObject无法知道具体的实例化类型,解析为了LinkedHashMap
解决方法,使用exchange方法替代:

Map param = new HashedMap();
param.put("key","value");//传入参数
parameterizedTypeReference =
                new ParameterizedTypeReference>(){};
//XXX为实例化的类型
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity entity = new HttpEntity<>(new Gson().toJson(param),headers);
ResponseEntity> result =                    
REST_TEMPLATE.exchange(url, HttpMethod.POST, entity,
                        parameterizedTypeReference);

你可能感兴趣的:(spring resttemplate泛型)