users@jersey.java.net

Re: using jersey with generic list of 0 elements

From: Jakub Podlesak <jakub.podlesak_at_oracle.com>
Date: Thu, 18 Nov 2010 14:34:41 +0100

This should work if you switch to using the JSON POJO mapping feature [1].
Attached is a simple application providing two resources:
an empty array and an array with mixed content.

To run, just unzip and launch mvn clean compile exec:java
then see:

http://localhost:9998/list/empty
http://localhost:9998/list/mixed-content

HTH,

~Jakub

[1]http://jersey.java.net/nonav/documentation/latest/json.html#d0e1960


On 11/09/2010 10:36 PM, vaidyaatdst_at_gmail.com wrote:
> Recently i started using jersey 1.4 specifically for its support of
> generics but am facing a problem when the no of elements in the list
> are 0.
>
>
> My setup
> ========
>
> Java(Resource) part
> ====================
> This is how my jersey resource code snippet looks as
>
> public class A<K extends SomeBasePeriod>
> {
> @GET
> @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML
> })
> @Path("periods")
> public List<K> getPeriods()
> {
> List<K> periods=new ArrayList<K>();
> if( periodsExist()) // the derived class would decide this..
> periods.add(createPeriods()); // this class could go to the
> derived class as well.
> // assume createPeriods returns "K" objects
> return periods;
> }
> }
>
> JavaScript(client) part
> =======================
> I have a java script which expects an array .
>
> Problem
> =========
> The problem that i am having is that when the periods above is an
> empty array list , I am getting "null" as the json response in the
> javascript and it bombs with "DataError:null"
>
> Tried Stuff
> ===========
> 1. Looks like folks have had this issue and have tried different work
> around
> http://markmail.org/search/?q=empty+element+to+json#query:empty%20eleme
> nt%20to%20json+page:1+mid:f2cnoh2o5kyjlmgg+state:results
>
> Did you guys get the resource to spit out { "items":[] } as suggested
> in the link?
>
> I tried to use XmlElementWrapper by adding
> @XmlElementWrapper(name="periods",required=true,nillable=false) but i
> am still getting null .
>
> 2. I cant use the other solution as it would force me to change the api
> (from List to Response as suggested by someone in the above thread).
>
> So how i can get the resource to spit out [] or atleast if i add the
> XmlElementWrapper (is there something that i am missing) to say {
> "periods":[] }
>
> Thanx a Lot
> Vaidya
>