RestTemplate中使用ParameterizedTypeReference参数化类型支持泛型

使用普通的RestTemplate.postForObject是无法知道泛型的具体类型的,需要借助ParameterizedTypeReference参数化类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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反序列化也支持泛型:

1
2
3
4
5
6
7
8
9
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>>>(){}
);

更多示例:

1
2
3
4
5
6
7
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));

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :