I am working on RestFul Webservice,i have written a small restful service, that returns a json data, here is my code :
@Path("/test")
public class TestService {
@GET
@Produces(MediaType.APPLICATION_JSON)
public String sayHello() {
return "<h6> Hello, Welcome to the world of REST (Plain Text) </h6>";
}
@GET
@Path("dbdetails")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, List> getDBDetails() {
System.out.println("ramesh kumar ");
List<ProductCategories> list = new ArrayList<ProductCategories>();
HashMap<String,List> map = new HashMap<String,List>();
ProductCategories cat = new ProductCategories();
cat.setId(1);
cat.setImage("Image21");
cat.setName("Electronics");
cat.setRowid(111);
cat.setType("CatType");
list.add(cat);
map.put("Ramesh",list);
System.out.println("ramesh kumar ");
return map;
}
But I am getting error :
SEVERE: A message body writer for Java type, class java.util.HashMap, and MIME media type, application/json, was not found Mar 3, 2011 3:32:41 PM com.sun.jersey.server.impl.application.WebApplicationImpl onException SEVERE: Internal server error javax.ws.rs.WebApplicationException
Any ideas?
Under the covers, Jersey uses JAXB for marshaling. First, if you haven't included the jersey-json artifact, it won't do JSON at all. That can cause the error that you posted. Second, JAXB uses annotations to determine how to marshal and unmarshal things. In order to marshal an object with JAXB, its class must be annotated with @XmlRootElement. If a class isn't annotated so, Jersey will think it doesn't know how to marshal the object, and again, you'll get that same error. I'm not 100% clear on the use of GenericEntity, having never needed it myself, but I don't think that will help you here. I believe there are two commonly-accepted solutions to your problem:
Most people tend to choose the second option, I think. You can find plenty of discussion about this issue in the jersey users mailing list archive.
This looks like type erasure scenario. You should use GenericEntity as return type. Your code should be something like:
public GenericEntity<Map<String, List>> getDBDetails() {
.
.
.
return new GenericEntity<Map<String, List>> (map) {};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With