Java 17 Spring Boot中instanceof判断响应类型失效问题
问题原因与解决办法
为什么instanceof判断无效?
当你用RestTemplate.exchange(..., Object.class)接收响应时,Jackson会根据返回的JSON结构自动生成对应的Java类型:
- 如果是JSON数组(有记录的情况),会被反序列化为
List<LinkedHashMap> - 如果是JSON对象(无记录的错误情况),会被反序列化为
LinkedHashMap
这两种类型都不是你定义的ZohoError或Leave,所以response.getBody() instanceof ZohoError永远为false,代码必然进入else分支。
解决方案一:先获取字符串响应,手动尝试反序列化
先把响应体以字符串形式接收,先尝试反序列化为ZohoError,失败则反序列化为List<Leave>:
HttpEntity<Void> request = new HttpEntity<>(httpHeaders); ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, request, String.class); ObjectMapper objectMapper = new ObjectMapper(); try { // 尝试解析为错误结构 ZohoError zohoError = objectMapper.readValue(response.getBody(), ZohoError.class); return Collections.emptyList(); } catch (JsonProcessingException e) { // 解析错误,说明是列表结构 List<Leave> leaves = objectMapper.readValue(response.getBody(), new TypeReference<List<Leave>>() {}); return leaves; }
解决方案二:用JsonNode判断结构后转换
借助JsonNode先判断响应体是否包含错误字段,再做对应转换:
HttpEntity<Void> request = new HttpEntity<>(httpHeaders); ResponseEntity<JsonNode> response = restTemplate.exchange(uri, HttpMethod.GET, request, JsonNode.class); JsonNode body = response.getBody(); ObjectMapper objectMapper = new ObjectMapper(); if (body != null && body.has("errorcode")) { // 检查是否存在错误字段 return Collections.emptyList(); } else { return objectMapper.convertValue(body, new TypeReference<List<Leave>>() {}); }
补充说明
- 你的
ZohoError类中@JsonAlias已经正确处理了字段名映射(比如errorcode对应errorCode),无需调整。 - 如果第三方API的错误结构有固定标识(比如特定的
responseStatus值),也可以在判断时加上更精准的条件,避免误判。
内容的提问来源于stack exchange,提问作者anonymous
相关产品推荐
相关产品推荐

