【问题标题】:Returning and Casting ResponseEntity<List<T>>返回和转换 ResponseEntity<List<T>>
【发布时间】:2018-11-19 13:54:46
【问题描述】:

我正在尝试返回一个 ResponseEntity 列表并将该响应投射到我的模型类中。

例如:如果我使用ResponseEntity&lt;List&lt;ApplicationModel&gt;&gt;,它运行良好,但我不想为每个模型编写响应方法。

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


    【解决方案1】:

    使用mapper.convertValue 对我有用。

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

    【讨论】:

      【解决方案2】:

      问题来自杰克逊。当它不够用时 关于要反序列化到哪个类的信息,它使用 LinkedHashMap。

      由于您没有通知杰克逊您的元素类型 ArrayList,它不知道你想反序列化成一个 ApplicationModels 的 ArrayList。所以它会回退到默认值。

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

      更多信息请参考java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

      【讨论】:

        猜你喜欢
        • 2020-05-23
        • 2012-07-22
        • 1970-01-01
        • 2017-03-29
        • 2014-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        相关资源
        最近更新 更多