2010-06-08 09:30:13.749730

I was using this blog post to configure the natural JSON convention in Jersey 1.2 for some RESTful web services I was using but it wasn't working. It took me a while to figure out what was wrong so I figured someone might have the same problem in the future. Here is the corrected class:

package com.webshop;

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

import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
import com.webshop.item.ItemBean;
import com.webshop.order.OrderBean;
import com.webshop.order.OrderItemBean;
import com.webshop.order.OrderList;

/**
* Custom JAXB context resolver that enables the "natural" json generator. The
* natural generator has nicer features, such as generating json arrays always
* properly, instead of only when the array has more than one element (makes
* the parsing easier)
*/
@Provider
public class CustomJAXBContextResolver implements ContextResolver {

    private JAXBContext context;
    private Class[] types = {OrderBean.class, OrderItemBean.class, ItemBean.class, OrderList.class};

    public CustomJAXBContextResolver() throws Exception {
        this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types);
    }

    public JAXBContext getContext(Class objectType) {
        for(Class c : types) {
             if(c.equals(objectType))
             return(context);
        }
        return(null);
    }
}

Please note that your class names may be different than mine

The gist of the issue was to ensure that the getContext() method returns the correct context for the given class. For some reason in the blog post linked above it was always only comparing to the first element in the array.

Jersey will automatically load your custom context resolver, just make sure that it is somewhere in the classpath.