2016-11-04 39 views
0

有沒有辦法強制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。但這很難看,因爲我必須手動設置標題和響應主體。

我希望有人知道更好的方法?

感謝

+0

怎麼樣的情況下,拋出一個異常該服務返回null/nothing,然後使用ExceptionHandler來設置適當的響應和頭? – Mubin

回答

1

如果你想所有響應返回application/json,那麼你可以在一個地方由HandlerInterceptorAdapter覆蓋postHandle()設置此:

@Component 
public class ResponseInterceptor extends HandlerInterceptorAdapter { 

    @Override 
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, 
      final ModelAndView modelAndView) throws IOException { 
     if (response.getContentType() == null || response.getContentType().equals("")) { 
      response.setContentType("application/json"); 
     } 
    } 
} 

你可以看看here

+0

非常感謝您,這正是我一直在尋找的內容。 – wybourn

0

,你可以換一個 「容器」 對象 例如響應我用這個BaseAjaxResponse:

public class BaseAjaxResponse implements Serializable 
{ 

    private static final long serialVersionUID = 9087132709920851138L; 
    private int codiceOperazione; 
    private String descrizioneEsitoOperazione; 
    private long numeroTotaleOggetti; 
    private long numeroOggettiRestituiti; 
    private List<? extends Object> payload; 
    //Constructors and getter/setter 

} 
在我的控制器

然後我用這個策略:

@RequestMapping(method = { RequestMethod.POST }, value = { "/find" }) 
    public ResponseEntity<BaseAjaxResponse> createCandidato(@RequestBody CandidatoDto candidato){ 
     BaseAjaxResponse bar = new BaseAjaxResponse(); 
     HttpStatus statusCode = null; 
     List<Object> payload = null; 
     StopWatch sw = new StopWatch("Find"); 
     try 
     { 
      sw.start(); 
      payload = myService.find(); 
      sw.stop(); 
      if(payload == null || payload.isEmpty()) 
      { 
       statusCode = HttpStatus.NO_CONTENT; 
       bar.setCodiceOperazione(statusCode.value()); 
       bar.setDescrizioneEsitoOperazione("No result"); 
      } 
      else 
      { 
       statusCode = HttpStatus.OK; 
       bar.setCodiceOperazione(statusCode.value()); 
       bar.setDescrizioneEsitoOperazione("Got result");  
       //Set the object count and the number of found objects 
      } 
     } 
     catch (Exception e) 
     { 
      String message = "Errore nell'inserimento di un candidato; "+e.getMessage(); 
      statusCode = HttpStatus.INTERNAL_SERVER_ERROR; 
      bar.setCodiceOperazione(statusCode.value()); 
      bar.setDescrizioneEsitoOperazione(message); 
      logger.error(message, e); 

     } 
     finally 
     { 
      if(sw.isRunning()) 
      { 
       sw.stop(); 
       if(logger.isDebugEnabled()) 
       { 
        logger.debug("CHIUSURA STOPWATCH FORZATA. "+sw.toString()); 
       } 
      } 
     } 

     return new ResponseEntity<BaseAjaxResponse>(bar, statusCode); 
    } 

我希望這可以有用

Ang ELO

+0

不幸的是,這將無法正常工作,因爲服務返回一個字符串。我正在處理很多其他服務,而且很不幸,我對任何重構都有限制。 – wybourn

+0

我真正需要的是將null或空字符串轉換爲空的json對象。包裝方法的問題是它添加字段,而我需要一個空的json對象。 – wybourn

+0

那麼你可以使用自定義的消息轉換器;在此消息轉換器中,您可以根據需要處理JSON –