有沒有辦法強制spring始終生成json,即使是沒有數據要返回的空json對象。 我們的服務通過另一項拒絕任何無效json響應的服務(不管狀態碼如何)。這並不好,但我們無法控制這一點。Spring Controller總是生成json
使用彈簧控制器,您可以告訴他們生成json,但只有在有內容返回時纔可以使用。有沒有一種快速和優雅的方式來使所有的反應成爲json?
@RequestMapping(value = "/test", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public
@ResponseBody
ResponseEntity<String> test(){
// if this returns null or an empty string the response body will be emtpy
// and the content-type header will not be set.
return service.getData();
}
這裏的簡單解決方法是簡單地添加一個if語句來檢查null。但這很難看,因爲我必須手動設置標題和響應主體。
我希望有人知道更好的方法?
感謝
怎麼樣的情況下,拋出一個異常該服務返回null/nothing,然後使用ExceptionHandler來設置適當的響應和頭? – Mubin