2014-03-25 30 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

注:请评论,如果我不采取的一些重要的护理。