users@jersey.java.net

Re: [Jersey] JSONJAXBContextResolver question...

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Wed, 13 May 2009 14:05:56 +0200

On May 12, 2009, at 8:07 PM, Rabick, Mark A (IS) wrote:

> My app is 'working' while I expect it not to be… I have a class
> that extends ContextResolver that lists the 'types' included in the
> JSONJAXBContext and for which the context should be returned:
>
> /**
> * A JSON/JAXB context resolver for marshalling and unmarshalling
> objects
> * in XML or JSON.
> */
> @Provider
> @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
> public final class JSONJAXBContextResolver implements
> ContextResolver<JAXBContext> {
>
> private final JAXBContext context;
>
> private final Set<Class> types;
>
> /*
> * The list of JAXB class types (top-level) need to be listed
> here.
> */
> private final Class[] cTypes = {NodeV1.class,
> EntityAttributeMapV1.class,
>
> java.util.ArrayList.class};
>
> /**
> * Constructor that initializes the set of classes this provider
> will
> * resolve for JAXB and JSON. The JSON configuration is set to
> the
> * 'natural' formatting.
> * @throws Exception On initialization error.
> */
> public JSONJAXBContextResolver() throws Exception {
>
> this.types = new HashSet(Arrays.asList(cTypes));
> this.context = new JSONJAXBContext(
> JSONConfiguration.natural().build(), cTypes);
> }
>
> /**
> * @see
> javax.ws.rs.ext.ContextResolver#getContext(java.lang.Class)
> */
> public JAXBContext getContext(Class<?> objectType) {
> return (types.contains(objectType)) ? context : null;
> }
> }
>
> If I call a resource that marshalls a class not in the Class[]
> cTypes array above, it still marshalls the entities as expected?
> I've noticed this since I've gone to Jersey 1.0.3.
>

That will work. It will just not use a JAXBContext instantiated by the
Jersey runtime rather than the one supplied by your
JSONJAXBContextResolver.

Paul.