users@jersey.java.net

[Jersey] can not unmarshal nested generic list in a wrapper

From: rocklee <minitip_at_gmail.com>
Date: Tue, 25 Jan 2011 06:39:19 -0800 (PST)

Hi all,

I'm new to jersey and just created a Generic response wrapper as following:

@XmlRootElement(name = "response")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"page", "limit", "total", "data"})
public class GenericResponse<T> implements Serializable {
        private static final long serialVersionUID = -3971806944073145864L;

        /**
         * Total amount of items available
         */
        private long total;
        
        /**
         * The page of the list to display
         */
        private long page;
        
        /**
         * The limit of return items
         */
        private long limit;
        
        @XmlAnyElement
        @XmlElementWrapper(name = "data")
        private List<T> data;
}

So that I can return paginated pojo elements like Customer, Product etc
using this wrapper as following:

@Path("/products")
public class ProductResource {
        @Autowired
        ProductDAO productDAO;

        @GET
        @Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
        public GenericResponse<Product> getProducts(
                        @DefaultValue("") @QueryParam("q") String q,
                        @DefaultValue("1") @QueryParam("page") int page,
                        @DefaultValue("10") @QueryParam("limit") int limit) {
                  GenericResponse<Product> response = new GenericResponse<Product>();
                response.setTotal(150);
                response.setLimit(limit);
                response.setPage(page);
                response.setData(productDAO.getProducts(q, page, limit));
                return response;
       }
}

This can generate xml and json response well, but when I try to consume the
resource using the code like following, it can fetch total, limit and page
successfully, but the data is always empty.

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
GenericResponse<Product> response = new GenericResponse<Product>();
response =
service.path("products").accept(MediaType.APPLICATION_XML).get(response.getClass());

// works well
System.out.println(response.getLimit());

// always empty
for (Product product : response.getData()) {
     System.out.println(product.getTitle());
}

I have been struggling with the problem, not sure where I'm doing wrong,
please help me or give some suggestions. Thanks a lot.

Lee
-- 
View this message in context: http://jersey.576304.n2.nabble.com/can-not-unmarshal-nested-generic-list-in-a-wrapper-tp5959000p5959000.html
Sent from the Jersey mailing list archive at Nabble.com.