users@jersey.java.net

Problems with jersey and json with collection of 0 elements..

From: vaidya nathan <vaidyaatdst_at_gmail.com>
Date: Wed, 10 Nov 2010 08:47:23 -0600

Hi All,

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" . We use yui libraries and they look for some
element in the datasource but bomb when they see "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%20element%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":[] } when returning json of "0" elements.

Thanx a Lot and glad that the email issues has been resolved..
Vaidya