users@jersey.java.net

Can a List<Integer> be serialized to JSON without being wrapped?

From: Chad McHenry <mchenryc_at_gmail.com>
Date: Fri, 22 May 2009 02:46:47 -0400

Is there a way to serialize a List<Integer> via JSON-JAXB?

If the list is a member of an @XmlRootElement (i.e. Foo below), which
is registered with the JAXBContextResolver, I can return a List<Foo>
and the nested List<Integer> will marshal fine.

Adding ArrayList (Arrays$ArrayList is not accessible) does not work,
nor does subclassing ArrayList to add the @XmlRootElement and register
with JAXBContextResolver.

$ > curl -X GET -H 'Content-type: application/json'
http://localhost/pinakes/api/media/raw
A message body writer for Java type, class java.util.Arrays$ArrayList,
and MIME media type, application/json, was not found

$ > curl -X GET -H 'Content-type: application/json'
http://localhost/pinakes/api/media/nested
{"list":["1","2","3"]}

$ > curl -X GET -H 'Content-type: application/json'
http://localhost/pinakes/api/media/nestedList
[{"list":["1","2","3"]},{"list":["1","2","3"]}]

$ > curl -X GET -H 'Content-type: application/json'
http://localhost/pinakes/api/media/subclass
null

=== Foo.java ===
@XmlRootElement
public class Foo {
    public List<Integer> list = Arrays.asList(1,2,3);
}
=== MyArray.java ===
@XmlRootElement
public class MyArray<E> extends ArrayList<E> {
}
=== Resource.java ===
...
    @GET
    @Path("/raw")
    public List<Integer> testRaw() {
        return Arrays.asList(1,2,3);
    }
    @GET
    @Path("/nested")
    public Foo testNested() {
        return new Foo();
    }
    @GET
    @Path("/nestedList")
    public List<Foo> testNestedList() {
        return Arrays.asList(new Foo(),new Foo());
    }
    @GET
    @Path("/subclass")
    public List<Integer> testSubclass() {
        List<Integer> list = new MyArray<Integer>();
        list.add(1);
        list.add(2);
        return list;
    }