RestTemplate中使用ParameterizedTypeReference参数化类型支持泛型
使用普通的RestTemplate.postForObject
是无法知道泛型的具体类型的,需要借助ParameterizedTypeReference
参数化类型
public <T> T post(String url, @NotNull HttpEntity requestEntity, ParameterizedTypeReference<T> parameterizedTypeReference) {
ResponseEntity<T> responseEntity = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
parameterizedTypeReference
);
return responseEntity.getBody();
}
ParameterizedTypeReference<TestModelType<List<TestModelBody>>> parameterizedTypeReference =
new ParameterizedTypeReference<TestModelType<List<TestModelBody>>>() {};
TestModelType<List<TestModelBody>> listTestModelType =
restTemplateUtils.get(testUrl, parameterizedTypeReference);
FastJson反序列化也支持泛型:
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
String jsonString = jsonStringEntity.getBody();
T body = JSONObject.parseObject(jsonString, clazz); // 直接传Class不能确定泛型
JSONObject.parseObject(
jsonString,
new TypeReference<TestModelType<List<TestModelBody>>>(){}
);
更多示例:
HttpEntity<ChannelsPayRequest> requestEntity = new HttpEntity<>(request, getHttpHeaders());
ParameterizedTypeReference<Result<ChannelsPayResponse>> parameterizedTypeReference =
new ParameterizedTypeReference<Result<ChannelsPayResponse>>() {};
ResponseEntity<Result<ChannelsPayResponse>> responseEntity = restTemplate.exchange(String.format("http://%s/channels/pay", channelService.getServiceAppName()),
HttpMethod.POST, requestEntity, parameterizedTypeReference);
Result<ChannelsPayResponse> payResult = responseEntity.getBody();
log.info(JSON.toJSONString(payResult));
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/26/using-parameterizedtypereference-in-resttemplate-to-parameterize-types-and-support-generics/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
RestTemplate中使用ParameterizedTypeReference参数化类型支持泛型
使用普通的RestTemplate.postForObject是无法知道泛型的具体类型的,需要借助ParameterizedTypeReference参数化类型
public <T> T post(String url, @No……
文章目录
关闭
共有 0 条评论