如何调用rest API which returns 两种不同类型的对象
How to call a rest API which returns object of two different types
我正在使用 Spring 的 RestTemplate 调用外部 API(我无法对其进行任何更改)。如果找到结果,API returns 响应将数组作为响应正文,否则 returns 响应将字符串作为响应正文,说明“未找到记录”。当我收到“找不到公司”消息时出现异常,因为我将 RestTemplate 调用类型转换为自定义对象
ResponseEntity<Student[]> studentDetails = restTemplate.getForEntity(studentUrl, Student[].class);
以上代码在 API returns 字符串消息“找不到记录”时抛出异常。
处理这种情况的最佳方法是什么?
那样的话,你大概可以这么用
ResponseEntity<Object> studentDetails = restTemplate.getForEntity(studentUrl, Object.class);
然后检查响应类型并转换结果。
我正在使用 Spring 的 RestTemplate 调用外部 API(我无法对其进行任何更改)。如果找到结果,API returns 响应将数组作为响应正文,否则 returns 响应将字符串作为响应正文,说明“未找到记录”。当我收到“找不到公司”消息时出现异常,因为我将 RestTemplate 调用类型转换为自定义对象
ResponseEntity<Student[]> studentDetails = restTemplate.getForEntity(studentUrl, Student[].class);
以上代码在 API returns 字符串消息“找不到记录”时抛出异常。 处理这种情况的最佳方法是什么?
那样的话,你大概可以这么用
ResponseEntity<Object> studentDetails = restTemplate.getForEntity(studentUrl, Object.class);
然后检查响应类型并转换结果。