How can I customize serialization of a list of JAXB objects to JSON?

I found a solution: replace the JAXB JSON serializer with a better behaved JSON serializer like Jackson. The easy way is to use jackson-jaxrs, which has already done it for you. The class is JacksonJsonProvider. All you have to do is edit your project’s web.xml so that Jersey (or another JAX-RS implementation) scans for it. Here’s what you need to add:

<init-param>
  <param-name>com.sun.jersey.config.property.packages</param-name>
  <param-value>your.project.packages;org.codehaus.jackson.jaxrs</param-value>
</init-param>

And that’s all there is to it. Jackson will be used for JSON serialization, and it works the way you expect for lists and arrays.

The longer way is to write your own custom MessageBodyWriter registered to produce “application/json”. Here’s an example:

@Provider
@Produces("application/json")
public class JsonMessageBodyWriter implements MessageBodyWriter {
    @Override
    public long getSize(Object obj, Class type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public boolean isWriteable(Class type, Type genericType,
            Annotation annotations[], MediaType mediaType) {
        return true;
    }

    @Override
    public void writeTo(Object target, Class type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap httpHeaders, OutputStream outputStream)
            throws IOException {        
        new ObjectMapper().writeValue(outputStream, target);
    }
}

You’ll need to make sure your web.xml includes the package, as for the ready-made solution above.

Either way: voila! You’ll see properly formed JSON.

You can download Jackson from here:
http://jackson.codehaus.org/

Leave a Comment