现有一个请求返回值的格式为:
{
"success": true,
"message": "",
"code": 200,
"result": {
"returnCode": "03AD",
"returnMsg": "AD3",
"qrcode": "https://xxxxxxxxxx3xxxxxaaAAAAAA",
"outTradeNo": "xxxxxx",
"bankTradeNo": null,
"msgId": "xxxx"
},
"timestamp": 16889873123011919
}
为了接收这个返回值,消费者这边建立了一个实体类接收这个返回值(考虑到返回值中的result内容会随着接口的改变而改变,使用了泛型):
@Data
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
private boolean success;
private String message;
private Integer code;
private T result;
private long timestamp;
}
使用RestTemplate.postForEntity()向生产者发送请求:
HttpHeaders headers = new HttpHeaders();
headers.put("TOKEN_SCRIPT",Arrays.asList(appToken));
OrderDTO orderDTO = txnReqBody.getOtherData();
HttpEntity<OrderDTO> httpEntity = new HttpEntity<>(orderDTO,headers);
ResponseEntity<Result> resultResponseEntity = restTemplateHttps.postForEntity(payQrCodeUrl, httpEntity, Result<PayOrderQueryResponse>.class); --会出现编译错误,不支持泛型
不使用泛型:
ResponseEntity<Result> resultResponseEntity = restTemplateHttps.postForEntity(payQrCodeUrl, httpEntity, Result.class);
发现result对象被解析成了LinkedHashMap
使用exchange加泛型解决问题
HttpHeaders headers = new HttpHeaders();
headers.put("TOKEN_SCRIPT",Arrays.asList(appToken));
OrderDTO orderDTO = txnReqBody.getOtherData();
HttpEntity<OrderDTO> httpEntity = new HttpEntity<>(orderDTO,headers);
ParameterizedTypeReference<Result<PayQrCodeResponse>> typeRef = new ParameterizedTypeReference<Result<PayQrCodeResponse>>() {};
ResponseEntity<Result<PayQrCodeResponse>> exchange = restTemplateHttps.exchange(payQrCodeUrl, HttpMethod.POST, httpEntity, typeRef);
解析正确。