我正在使用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