Reputation: 4691
I am using Gson library to handle parsing Json to java entities and vice-versa. Now, after processing the in need to return the Json object to the caller. But doing so results in following exception:
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 after processing is {"status":"Entity added successfully."}
My Observation: It seems like i need to register Gson
implementation for Json somewhere to let the container know that I will send Json data using Gson's JsonObject. If i observed correctly, then where should i register and how, or if i am totally wrong then, please correct me.
My implementation looks like following:
@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();
}
Upvotes: 0
Views: 1747
Reputation: 4691
I figured out the usage of 'MessageBodyReader' and 'MessageBodyWriter' and i found that need of implementing these two interfaces was just to put the parsing logic separate from the core business logic. Since i already had parser implemented for me, so i had to shift my parse code to take advantage of interfaces.
So, i decided to return the String
and set the response type as Json
, since i had Json string already available after processing.
So now my code looks like:
@Produces(MediaType.APPLICATION_JSON)
public String addEntity(@FormParam("entity") String jsonEntity, @FormParam("entityType") String jsonEntityType) {
JsonObject jSonStatus = null;
....
....
return JsonStatus.toString;
}
To checked the response in Advance Rest client
, it showed correct Json with Content-Type: application/json
Note: Please comment if i am not taking care of something important.
Upvotes: 1