2014-03-25 70 views
0

我正在使用Gson庫來處理解析Json到Java實體,反之亦然。 現在,處理之後需要將Json對象返回給調用者。 但這樣做在以下例外,這樣的結果:從Rest-Webservice發送Json [Gson實現]

的Json後
Mar 25, 2014 4:46:30 PM com.sun.jersey.spi.container.ContainerResponse write 
SEVERE: A message body writer for Java class com.google.gson.JsonObject, and Java type class com.google.gson.JsonObject, and MIME media type application/json was not found 
Mar 25, 2014 4:46:30 PM com.sun.jersey.spi.container.ContainerResponse write 
SEVERE: The registered message body writers compatible with the MIME media type are: 

處理是{"status":"Entity added successfully."}

我的觀察:好像我需要註冊Gson實施JSON的地方,讓容器知道我會使用Gson的JsonObject發送Json數據。如果我觀察正確,那麼我應該在哪裏註冊以及如何,或者如果我完全錯誤,那麼請糾正我。

我的實現看起來如下:

@POST 
@Path("/entity") 
@Produces(MediaType.APPLICATION_JSON) 
public Response addEntity(@FormParam("entity") String jsonEntity, @FormParam("entityType") String jsonEntityType) { 
    JsonObject jSonStatus = null; 
    log.info("Entered webservice method: " + jsonEntity.toString() + "\n" + jsonEntityType.toString()); 
    if (jsonEntity != null && jsonEntityType != null) { 
     dispatcher = dispatcher.getDispatcher(); 
     jSonStatus = dispatcher.addEntity(jsonEntity, jsonEntityType); 
    } 
    log.info("Returning from webservice method: " + jSonStatus); 
    ResponseBuilder rb = new ResponseBuilderImpl(); 
    // rb.type(MediaType.APPLICATION_JSON); tried with this also, but no luck 
    rb.entity(jSonStatus); 
    rb.status(Status.OK); 

    return rb.build(); 
} 
+0

我能想到的一個選擇是返回普通的'String',因爲json只是組織'String'。 – guptakvgaurav

+0

請檢查這個答案:http://stackoverflow.com/questions/9516224/using-gson-instead-of-jackson-in-jersey – Wintermute

+0

@Wintermute建議的鏈接指導我正確的方向,但也是他們的任何參考文檔除了javadoc之外的實現,如果鏈接中提到'Writer'類 – guptakvgaurav

回答

1

我想通了,「化MessageBodyReader」和「MessageBodyWriter」的使用,我發現需要實現這兩個接口的只是把解析邏輯從分離核心業務邏輯。由於我已經爲我執行了解析器,所以我不得不移動我的解析代碼以利用接口。

因此,我決定返回String並設置response type as Json,因爲我的Json字符串在處理後已經可用。

所以現在我的代碼如下所示:

@Produces(MediaType.APPLICATION_JSON) 
    public String addEntity(@FormParam("entity") String jsonEntity, @FormParam("entityType") String jsonEntityType) { 
     JsonObject jSonStatus = null; 
     .... 
     ....  
     return JsonStatus.toString; 
} 

要檢查在Advance Rest client的反應,這表明正確的Json與Content-Type: application/json

注:請評論,如果我不採取的一些重要的護理。