统一泛型返回对象
@Data
public class Res<T> implements Serializable {private static final long serialVersionUID = 6558796578827818466L;private Integer code; //状态码private String msg; //返回消息private T data; //数据
}
data里包裹的泛型对象假设是DZPJ
@Data
public class DZPJ implements Serializable {private String billNo;//发票号码
}
postForEntity或postForObject接收参数多层泛型用下面这种方式接收参数会抛出类型转换异常
Res<DZPJ> res = restTemplateBuilder.build().postForEntity(requestUrl, new HttpEntity<>(dto, headers), Res.class).getBody();//此时这里会抛出java.util.LinkedHashMap cannot be cast to DZPJDZPJ dzpj = res.getData();
正确做法
Res<DZPJ> res = restTemplateBuilder.build().exchange(requestUrl, HttpMethod.POST, new HttpEntity<>(dto, headers), new ParameterizedTypeReference<Res<DZPJ>>() {}).getBody();//这里就可以正常解析了。DZPJ dzpj = res.getData();