Friday, October 3, 2008

Collections and JAX-RS

As I had previously reported, both RestEasy and Jersey both suffered from the inability to return a collection of JAXB marshalled objects. I was thinking on this a little, and while I could use the JAXBCollection fix in Jersey, it seemed a little bit of a hack until it goes into the 1.0 release. Instead (for now), I have written a few wrapper classes which they themselves are XmlRootElements thus supporting marshalling with JAXB. This actually worked and is a reasonable workaround (since I really only need to return collections for four to five persistent objects. These wrapper objects simply have a collection/list of the persistent objects with the XmlElement set to have the appropriate name of the child elements for processing:

package org.javad.stamp.model.collections; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.javad.stamp.model.Country; @XmlRootElement(name="countryList") public class CountryList { @XmlTransient public List countries = new ArrayList(); public CountryList( ) { } public void setCountries( List c ) { countries = c; } @XmlElement(name="country") public List getCountries() { return countries; } public void addCountry( Country c ) { countries.add(c); } }

2 comments:

Unknown said...

Great advice! This was extremely useful to me!

I am currently stuck with Beta 5 of RESTeasy because Seam only supports this version right now (I know, tell me about it!).

One thing I might say, using your approach successfully, is to add @XmlSeeAlso(..) to your wrapper class, so that JAXB can find the item of the collection! Otherwise you'll get a "Marshalling Error: class [...] nor any of its super class is known to this context".

Cheers,
Stephan

Mats Henricson said...

Thanks from me as well - this was what helped me through some vague error messages from Jetty!