Home > Enterprise >  How to call a rest API which returns object of two different types
How to call a rest API which returns object of two different types

Time:01-06

I am calling an external API (on which I do not have a control to make any change) using Spring's RestTemplate. The API returns response with an array as response body if the results are found and if not it returns response with String as response body stating "No records found". I am getting an exception when I am getting the no company found message because I typecasted the RestTemplate call to the custom object

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

The above code throws exception when the API returns String message "No records found". What is the best way to deal with such a scenario?

CodePudding user response:

In that case, you probably may use it like that

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

And then check for the response type and cast the result.

  •  Tags:  
  • Related