返回并投射ResponseEntity <list <t>&gt;

时间:2018-06-09 21:24:42

标签: java spring spring-mvc spring-boot spring-rest

我正在尝试返回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, “名称”: “foo” 的, “说明”: “foo” 的}

错误

  

出现意外错误(type = Internal Server Error,status = 500)。   创建名为'index'的bean时出错:init方法的调用失败;嵌套异常是java.lang.ClassCastException:java.util.LinkedHashMap无法强制转换为com.xxx.ApplicationModel

2 个答案:

答案 0 :(得分:1)

  

这个问题来自杰克逊。当它没有足够的时候   有关要反序列化的类的信息,它使用LinkedHashMap。

     

由于您未通知杰克逊您的元素类型   在ArrayList中,它不知道你想要反序列化为    ApplicationModels 的ArrayList。所以它回归到默认值。

     

相反,您可以使用as(JsonNode.class),然后处理   ObjectMapper以比放心的方式更丰富的方式允许。

有关其他信息,请参阅java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

答案 1 :(得分:0)

使用mapper.convertValue对我有用。

ObjectMapper mapper = new ObjectMapper();
List<ApplicationModel> dtoApplications = mapper.convertValue(responseForApproles.getBody(), new TypeReference<List<ApplicationModel>>() {});
相关问题