users@jersey.java.net

JAXBContext and Resolvers

From: David Sells <dsells_at_gmail.com>
Date: Thu, 27 Aug 2009 12:23:46 -0400

Hi Paul et al.

I am trying to get a simple example working. We have a one-to-many
association. So there is a parametrized collection that needs to be
serialized through JAXB.
I can set the getPersons method to return an array Person[] and it will work
fine. So we have the basic configuration set-up correctly.

I would like to use a ContextResolver to add a transformation to the
JAXBContext. I added the code below this message. So that when I run the
application I exect to see the message "We have entered the OurResolver".
Instead we get:

 java.io.IOException: Error marshalling JAXB object of type "class
java.util.ArrayList".

So I'm thinking that I must be missing something fundemental here. If you
can shed any light on this problem I would appreciate it. Note that this is
being run in a Spring environment.

Thanks, David


/**
 *
 */
package com.persistent.converter;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.persistent.entity.Company;
import com.persistent.entity.Person;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;

/**
 * @author david
 *
 */

@Component
@Provider
public class OurResolver implements ContextResolver<JAXBContext> {
    private Logger log = Logger.getLogger(this.getClass());
      private final JAXBContext context;

      private final Class<?>[] types = { Person.class,Company.class };

     public OurResolver() throws Exception {
            try{
            this.context = new
JSONJAXBContext(JSONConfiguration.natural().build(), types);
            }catch(Exception e) {
                log.error("Exception thrown creating OurResolver:
"+e.getMessage());
                throw e;
            }
        }


    public JAXBContext getContext(Class<?> objectType) {
        log.info("We have entered the OurResolver");
         for (Class<?> type : types) {
                             if (type == objectType) {
                                 return context;
                             }
                         }
                         return null;
    }
}