[英]Sending Json [Gson implementation] from Rest-Webservice
我正在使用Gson庫來將Json解析為Java實體,反之亦然。 現在,在處理完之后,需要將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:
處理后的Json是{"status":"Entity added successfully."}
我的觀察 :似乎我需要在某個地方注冊Json的Gson
實現,以使容器知道我將使用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();
}
我弄清楚了'MessageBodyReader'和'MessageBodyWriter'的用法,發現實現這兩個接口的需要僅僅是將解析邏輯與核心業務邏輯分開。 由於我已經為我實現了解析器,因此我不得不移動解析代碼以利用接口。
因此,我決定返回String
並將response type as Json
設置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
檢查響應,它使用Content-Type: application/json
顯示了正確的Json Content-Type: application/json
注意:如果我不注意重要事項,請發表評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.