Hi Christopher,
Have you verified that you can use marshall ImmutableSausage using
stand alone JAXB?
I did a quick test and it is not possible to marshall an instance of
ImmutableSausage. You will get an exception like the following:
Exception in thread "main"
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1
counts of IllegalAnnotationExceptions
Main$ImmutableSausage does not have a no-arg default constructor.
this problem is related to the following location:
at Main$ImmutableSausage
if you try:
JAXBContext c =
JAXBContext.newInstance(ImmutableSausage.class, SausageBean.class);
StringWriter sw = new StringWriter();
c.createMarshaller().marshal(new ImmutableSausage(1), sw);
or:
Exception in thread "main" javax.xml.bind.JAXBException: class Main
$ImmutableSausage nor any of its super class is known to this context.
if you try:
JAXBContext c = JAXBContext.newInstance(SausageBean.class);
StringWriter sw = new StringWriter();
c.createMarshaller().marshal(new ImmutableSausage(1), sw);
Thus i don't think you can use the XmlAdapter to transform to/from an
XML root element.
In this case you will need to write your own message body writer for
ImmutableSausage.
Paul.
On Aug 10, 2010, at 9:01 PM, Christopher Piggott wrote:
> Hi,
>
> I understand about messagebodywriters but I'm trying to figure out a
> way for this to happen more automatically. Here's the situation:
>
> I have an object that's not a true POJO in the sense that it has no
> default constructor and it's immutable, e.g.:
>
> public class ImmutableSausage {
> final int bites;
> public ImmutableSausage(int numBites) { bites = numBites; }
> public int getBites() { return bites; }
> }
>
> I haven't totally figured out this works, but I gather that to
> serialize this I make:
>
> @XmlElement
> @XmlJavaTypeAdapter(SausageAdapter.class)
> public class SausageBean {
> int bites;
> public void setBites( int numBites) { bites = numBites; }
> @XmlAttribute
> public int getBites() { return bites; }
> }
>
> then I create a SausageAdapter implements XmlAdapter<SausageBean,
> ImmutableSausage>
>
> (this is where I get to the jersey part)
>
> @GET
> @Produces("application/xml")
> ImmutableSausage getSausage()
> {
> return new ImmutableSausage(12);
> }
>
>
> so, my resource method returns something that is not at all a bean,
> but 1. jaxb knows what to do with it because of the
> XmlJavaTypeAdapter 2. it's all handled by jaxb so that I don't need
> MessageBodyReaders or MessageBodyWriters
>
> Do I understand this correctly, and should it work?
>
> --C
>
>