【发布时间】:2018-11-19 13:54:46
【问题描述】:
我正在尝试返回一个 ResponseEntity 列表并将该响应投射到我的模型类中。
例如:如果我使用ResponseEntity<List<ApplicationModel>>,它运行良好,但我不想为每个模型编写响应方法。
ResponseEntity方法
public static <T> ResponseEntity<List<T>> getResponseList(String resourceURL) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<List<T>> entity = new HttpEntity<List<T>>(headers);
ResponseEntity<List<T>> response = restTemplate.exchange(resourceURL, HttpMethod.GET, entity,
new ParameterizedTypeReference<List<T>>() {
}, Collections.emptyMap());
return response;
}
方法调用
private final String url ="http://localhost:8090/xxx/application";
ResponseEntity<List<ApplicationModel> responseForApplications =
ResponseTemplate.getResponseList(url);
if (responseForApplications.getStatusCode() == HttpStatus.OK)
List<ApplicationModel> dtoApplications = responseForApplications.getBody();
我要转换的 JSON 响应示例
{"id":1,"name":"foo","description":"foo"}
错误
出现意外错误(类型=内部服务器错误,状态=500)。 创建名为“index”的 bean 时出错:调用 init 方法失败;嵌套异常是 java.lang.ClassCastException: java.util.LinkedHashMap 不能转换为 com.xxx.ApplicationModel
【问题讨论】:
标签: java spring spring-mvc spring-boot spring-rest