users@jersey.java.net

[Jersey] JSON: Integervalues of ArrayList<Integer> have quotes (in natural notation setting)

From: Peff <peff_at_gmx.at>
Date: Tue, 4 Jan 2011 21:22:48 +0100

Hi together,

In order to solve two common issues with the json parser (no brackets with
arrays of the size 1, integers have quotes like strings) i use the
JSONConfiguration.natural().build() configuration.

With that configuration I have to new problems now and I would be happy if
you could help me.

1. When a ArrayList<Integer> is being parsed (/A/), the integer values are
returned as if they were strings. So /A/ returns:
{"list1":["1","3"],"nummer":2,"nummer2":99} where I expect it to return
{"list1":[1,3],"nummer":2,"nummer2":99} since 1 and 3 are integers. When an
Integer like nummer2 is parsed as a normal variable it is correctly parsed
as integer.
Does somebody have a recommendation how I get jersey to pars these values as
integers?

2. My seconds questions concerns /B/. The only solution I found so far was
to explicitly list all class names in cTypes to parse them later on with the
natural setting. It seems to be a pain to write all the 60 different classes
in this list (and I'm surly will forget some in the future) so I'm looking
for a possibility to simply tell jersey to always use the natural setting.
Does somebody know if and how this is possible?

Thank you very much for your help!

Stefan Peff

-----------------------------------
Jersey-bundle-1.4

A ---------------------------------

        @Path("arraylistetest")
        @GET
        @Produces(MediaType.APPLICATION_JSON)
        public TestArrayList arraylisteTest() {
                TestArrayList testArrayList = new TestArrayList();
                return testArrayList;
        }

B ---------------------------------

@Provider
public final class JAXBContextResolver implements
ContextResolver<JAXBContext> {
    
    private final JAXBContext context;
    
    private final Set<Class> types;
    
    private final Class[] cTypes = {TestArrayList.class};
    
    public JAXBContextResolver() throws Exception {
        this.types = new HashSet(Arrays.asList(cTypes));
        this.context = new
JSONJAXBContext(JSONConfiguration.natural().build(), cTypes);
    }
    
    public JAXBContext getContext(Class<?> objectType) {
        return (types.contains(objectType)) ? context : null;
    }
}

C ------------------------------------

@XmlRootElement
public class TestArrayList {
        @XmlElement
        public ArrayList<Integer> list1;
        @XmlElement
        public int nummer;
        @XmlElement
        public Integer nummer2;
        
        public TestArrayList() {
                super();
                list1 = new ArrayList<Integer>();
                list1.add(1);
                nummer = 2;
                nummer2 = 99;
        }
}