2014-01-22 21 views
3

我正在運行Jersey 2.5.1 & Jackson在Tomcat休息應用程序中。對於我簡單地將POJO轉換爲JSON的初始用例,基本設置很有用。集是很好的轉化到一個JSON數組是這樣的:如何在送出之前包裹球衣+傑克遜json反應

[{//one item},{//second item},{}... and so on] 

現在,我需要檢查我送回到我的REST API和
1的結果),如果它是一個表或一組,然後把它轉換爲是這樣的:

{result:[//my original list of result objects]} 


2)如果它是一個簡單的POJO,然後把它轉換爲是這樣的:

{result:[{//the one result object}]} 

我甲肝e感覺這應該很簡單,但是,我沒有發現任何能夠顯示如何做到這一點的東西。有誰知道如何做到這一點?我試圖註冊一個Provider,然後註冊一個對象映射器和其他方法 - 沒有一個看起來簡單或者簡單...這些選項看起來像是太多的代碼,只是將我的對象包裹起來。

謝謝!

回答

4

創建Result類:

public class Result { 

    private List<YourItem> result; 

    // getters/setters 
} 

創建WriterInterceptor它包裝你的實體爲Result,讓傑克遜當元帥的結果對象:

@Provider 
public class WrappingWriterInterceptor implements WriterInterceptor { 

    @Override 
    public void aroundWriteTo(final WriterInterceptorContext context) 
      throws IOException, WebApplicationException { 

     final Result result = new Result(); 
     final Object entity = context.getEntity(); 

     if (entity instanceof YourItem) { 
      // One item. 
      result.setResult(Collections.singletonList((YourItem) entity)); 
     } else { 
      result.setResult((List<YourItem>) entity); 
     } 

     // Tell JAX-RS about new entity. 
     context.setEntity(result); 

     // Tell JAX-RS the type of new entity. 
     context.setType(Result.class); 
     context.setGenericType(Result.class); 

     // Pass the control to JAX-RS. 
     context.proceed(); 
    } 
} 
+0

可能的工作!讓我試試這個,讓你知道! – doles