开发者

Having problems getting a List of Objects back from Restful service

Hey guys. I've developed some services in REST that are running on Glassfish 3.1.

I have a Java SE application and I am using Jersey as the client api.

 public <T> T findAll_JSON(Class<T> responseType) throws UniformInterfaceException {
    WebRes开发者_JAVA百科ource resource = webResource;
    return resource.accept(MediaType.APPLICATION_JSON).get(responseType);
}

This is the client code that is generated by Netbeans.

My main problem is passing a list of objects as the response type

Here is the client code.

   List<PkgLine> pkgLine = service.findAll_JSON(List.class);        
    System.out.println(pkgLine.get(5).getLineStatus());          
    service.close();

Obviously this is not working because the response needs to be a List of PkgLine. How do I pass that as a generic? My service is set to return the List of PkgLine. Thanks.


The problem is "erasure". You can declare a List<PkgLine> in your program, but at runtime the information that the objects in the List are PkgLines is erased. List<String>, List<PkgLine> and List<Object> are all the same type at runtime. (There's a reason why this is so; I won't explain it here but you can look up "erasure" if you are interested.)

The objects in the List are still PkgLines of course, but to the List they are just Objects, and you'll have to cast each one to a PkgLine. It's not pretty.

List<?> pkgLine = service.findAll_JSON(List.class);
System.out.println(((PkgLine)(pkgLine.get(5))).getLineStatus());
service.close();


What about parsing an array? It has the same json represantation. You could write something like this:

resource.accept(MediaType.APPLICATION_JSON).get(PkgLine[].class);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜