You are previewing RESTful Java with JAX-RS.

RESTful Java with JAX-RS

Cover of RESTful Java with JAX-RS by Bill Burke Published by O'Reilly Media, Inc.
O'Reilly logo

Custom Marshalling

So far in this chapter, we’ve focused on built-in JAX-RS handlers that can marshal and unmarshal message content. Unfortunately, there are hundreds of data formats available on the Internet and the built-in JAX-RS handlers are either too low-level to be useful or may not match the format you need. Luckily, JAX-RS allows you to write your own handlers and plug them into the JAX-RS runtime.

To illustrate how to write your own handlers, we’re going to pretend that there is no built-in JAX-RS JAXB support and instead write one ourselves using JAX-RS APIs.

MessageBodyWriter

The first thing we’re going to implement is JAXB-marshalling support. To automatically convert Java objects into XML, we have to create a class that implements the javax.ws.rs.ext.MessageBodyWriter interface:

public interface MessageBodyWriter<T> {

   boolean isWriteable(Class<?> type, Type genericType,
                       Annotation annotations[],
                                    MediaType mediaType);


   long getSize(T t, Class<?> type, Type genericType,
                 Annotation annotations[], MediaType mediaType);


   void writeTo(T t, Class<?> type, Type genericType,
                Annotation annotations[],
                MediaType mediaType,
                MultivaluedMap<String, Object> httpHeaders,
                OutputStream entityStream)
                       throws IOException, WebApplicationException;
}

The MessageBodyWriter interface only has three methods. The isWriteable() method is called by the JAX-RS runtime to determine if the writer supports marshalling the given type. The getSize() method is called by the JAX-RS runtime to determine the ...

The best content for your career. Discover unlimited learning on demand for around $1/day.