users@jersey.java.net

array handling in JAXB to JSON conversion

From: Moiz Dohadwala <mdohadwala_at_mokafive.com>
Date: Tue, 3 Mar 2009 12:14:17 -0800

Hello,

I have a list of objects that I need to stream out as JSON to a YUI datatable using JAXB.

Essentially, the simplified object model is:

@XmlRootElement
 class ItemList {
            @XmlElement(name="items")
            List<Item> items;

            long totalCount;
}

 class Item {
            String field1;
String field2;
}

The json needs to look like:

{
             Items :[ {field1: value1, field2: value2}, {field1: value3, field2:value4}
],
totalCount: 2
}

The totalCount is used in pagination.

It works well so long as we have a list size >0. If it is an empty list, The json comes out as:

{
totalCount: 0
}

This causes the YUI table to display "Data Error" instead of "No records found".

I have specified the JSONConfiguration as below:

JSONConfiguration.MappedBuilder builder = JSONConfiguration.mapped();
builder.rootUnwrapping(true);
builder.arrays("items");
builder.nonStrings("totalCount");

Class<?>[] types = {ItemList.class, Item.class};
JSONConfiguration configuration = builder.build();
this.context = new JSONJAXBContext(configuration,types);


is there a way to force an empty array field in the json?

Thank you.

-Moiz