我正在使用 Spring 的 RestTemplate 呼叫外部 API(我無法控制對其進行任何更改)。如果找到結果,API 將回傳一個帶有陣列的回應作為回應主體,如果沒有,它回傳帶有字串的回應作為回應主體,說明“未找到記錄”。當我收到 no company found 訊息時出現例外,因為我將 RestTemplate 呼叫型別轉換為自定義物件
ResponseEntity<Student[]> studentDetails = restTemplate.getForEntity(studentUrl, Student[].class);
當 API 回傳字串訊息“未找到記錄”時,上述代碼拋出例外。處理這種情況的最佳方法是什么?
uj5u.com熱心網友回復:
在那種情況下,你可能會這樣使用它
ResponseEntity<Object> studentDetails = restTemplate.getForEntity(studentUrl, Object.class);
然后檢查回應型別并轉換結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404719.html
標籤:
