【问题标题】:How to call a rest API which returns object of two different types如何调用返回两种不同类型对象的rest API
【发布时间】:2022-01-05 09:53:32
【问题描述】:

我正在使用 Spring 的 RestTemplate 调用外部 API(我无法对其进行任何更改)。如果找到结果,API 将返回带有数组作为响应主体的响应,否则返回带有字符串作为响应主体的响应,说明“未找到记录”。当我收到 no company found 消息时出现异常,因为我将 RestTemplate 调用类型转换为自定义对象

ResponseEntity<Student[]> studentDetails = restTemplate.getForEntity(studentUrl, Student[].class);

上述代码在API返回字符串消息“No records found”时抛出异常。 处理这种情况的最佳方法是什么?

【问题讨论】:

  • 您可能希望使用一些包装对象作为响应,它具有Student[] 属性,也可能还有String 消息属性。或者您可以发送 404 响应。

标签: java spring spring-boot spring-mvc


【解决方案1】:

这样的话,你可能会这样使用它

ResponseEntity<Object> studentDetails = restTemplate.getForEntity(studentUrl, Object.class);

然后检查响应类型并转换结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-18
    • 2022-01-24
    • 2021-07-03
    • 2021-03-22
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多