users@jersey.java.net

Re: [Jersey] XmlJavaTypeAdapter and jersey

From: Jason Winnebeck <gillius-ml_at_gillius.org>
Date: Wed, 11 Aug 2010 08:48:40 -0400

First off, sausage is great.

I tried this too and I couldn't get it to work. It seems that the two
workarounds are to make a wrapper (which changes the XML output):

@XmlRootElement( name = "SausageWrapper" )
public static class Wrapper {
        ImmutableSausage sausage;

        @XmlJavaTypeAdapter( SausageAdapter.class )
        public ImmutableSausage getSausage() {
                return sausage;
        }

        public void setSausage( ImmutableSausage sausage ) {
                this.sausage = sausage;
        }
}

Or, call the XmlAdapter (or a class like it) yourself:
c.createMarshaller().marshal(
   new SausageAdapter().marshal( new ImmutableSausage( 1 ) ),
   sw );

 From a resource bean method it would probably mean instead:

return new SausageAdapter().marshal( whatIReallyWanted );

But this would require changing your method signature.

I bet it would be possible to make a generic MessageBodyWriter that could be
given a set of XmlAdapters and build a map of all of the types it can write
with JAXB, so that you wouldn't need to change the signature of the resource
bean. I'm too new to Jersey to know if you can have a MessageBodyWriter that
can just delegate to Jersey's built-in JAXB though.

Jason

On 8/11/2010 5:26 AM, Paul Sandoz wrote:
> I did a quick test and it is not possible to marshall an instance of
> ImmutableSausage.

<snip>

>
> 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.