开发者

Problem with Restful WebService

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 ProductCatego开发者_运维问答ries();
    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:

  1. Wrap your Map in a JAXBElement.
  2. Write your own wrapper for the map which is annotated with @XmlRootElement.

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) {};
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜