On Nov 14, 2008, at 11:36 PM, Jeremy Whitlock wrote:
> Hello all,
> Alright, I have created a simple Jersey app that utilizes JAXB
> to take collections of objects and return a JSON/XML representation
> for
> the collections. What I found was actually pretty interesting and
> here
> is a brief summary:
>
> 1) Generic list support: While Jersey does not include an element for
> each array element, it shouldn't be necessary. (For example:
> List<Person>.)
> 2) Array support: Jersey seemed to have a problem taking an array of
> objects and serializing them to JSON/XML. I kept getting errors about
> no content writer being available. (For example: Person[].)
Below is the a resource class and methods from the unit tests of the
JAXB sample . This should make its way to the repo in about an hour or
two.
As you can see it is much nicer to user arrays on the client side
rather than using the generic wrapper classes to retain generic type
information.
Paul.
@Path("jaxb/array")
@Produces("application/xml")
@Consumes("application/xml")
public class JAXBArrayResource {
@Path("XmlRootElement")
@GET
public JAXBXmlRootElement[] getRootElement() {
List<JAXBXmlRootElement> el = new
ArrayList<JAXBXmlRootElement>();
el.add(new JAXBXmlRootElement("one root element"));
el.add(new JAXBXmlRootElement("two root element"));
el.add(new JAXBXmlRootElement("three root element"));
return el.toArray(new JAXBXmlRootElement[el.size()]);
}
@Path("XmlRootElement")
@POST
public JAXBXmlRootElement[] postRootElement(JAXBXmlRootElement[]
el) {
return el;
}
@Path("XmlType")
@POST
public JAXBXmlRootElement[] postXmlType(JAXBXmlType[] tl) {
List<JAXBXmlRootElement> el = new
ArrayList<JAXBXmlRootElement>();
for (JAXBXmlType t : tl)
el.add(new JAXBXmlRootElement(t.value));
return el.toArray(new JAXBXmlRootElement[el.size()]);
}
}
public void testRootElementArray() {
JAXBXmlRootElement[] ae1 = r.path("jaxb/array/XmlRootElement").
get(JAXBXmlRootElement[].class);
JAXBXmlRootElement[] ae2 = r.path("jaxb/array/XmlRootElement").
type("application/xml").
post(JAXBXmlRootElement[].class, ae1);
assertEquals(ae1.length, ae2.length);
for (int i = 0; i < ae1.length; i++)
assertEquals(ae1[i], ae2[i]);
}
public void testXmlTypeArray() {
JAXBXmlRootElement[] ae1 = r.path("jaxb/array/XmlRootElement").
get(JAXBXmlRootElement[].class);
JAXBXmlType[] at1 = r.path("jaxb/array/XmlType").
type("application/xml").
post(JAXBXmlType[].class, ae1);
JAXBXmlType[] at2 = r.path("jaxb/array/XmlRootElement").
get(JAXBXmlType[].class);
assertEquals(at1.length, at2.length);
for (int i = 0; i < at1.length; i++)
assertEquals(at1[i], at2[i]);
}