我正在使用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();
}
我能想到的一個選擇是返回普通的'String',因爲json只是組織'String'。 – guptakvgaurav
請檢查這個答案:http://stackoverflow.com/questions/9516224/using-gson-instead-of-jackson-in-jersey – Wintermute
@Wintermute建議的鏈接指導我正確的方向,但也是他們的任何參考文檔除了javadoc之外的實現,如果鏈接中提到'Writer'類 – guptakvgaurav