返回和转换 ResponseEntity<List<T>>

Posted

技术标签:

【中文标题】返回和转换 ResponseEntity<List<T>>【英文标题】:Returning and Casting 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

【问题讨论】:

【参考方案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。

【讨论】:

以上是关于返回和转换 ResponseEntity<List<T>>的主要内容,如果未能解决你的问题,请参考以下文章

ResponseEntity,如何获取html中的body

Spring boot - WebFlux - WebTestClient - 将响应转换为 responseEntity

如何使用 ResponseEntity 返回 JSONObject 而不是 HashMap? (未找到类型返回值的转换器:类 org.json.JSONObject)

Spring Boot RestController 中返回 void 和 ResponseEntity<Void> 有啥区别?

使用ResponseEntity进行返回json数据

webflux spring boot 应用程序的过滤器,返回 ResponseEntity<?>