users@jersey.java.net

Re: [Jersey] XmlJavaTypeAdapter and jersey

From: Paul Sandoz <Paul.Sandoz_at_oracle.com>
Date: Wed, 11 Aug 2010 15:55:29 +0200

On Aug 11, 2010, at 2:48 PM, Jason Winnebeck wrote:

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

It is possible. Inject Providers and use:

https://jsr311.dev.java.net/nonav/releases/1.1/javax/ws/rs/ext/Providers.html
#getMessageBodyWriter%28java.lang.Class,%20java.lang.reflect.Type,
%20java.lang.annotation.Annotation[],%20javax.ws.rs.core.MediaType%29

Paul.