Java Reference
In-Depth Information
The Jackson framework's JAX-RS integration actually does all this work for you, so all you
have to do in your JAX-RS classes is specify the output and input format as
application/
json
when writing your JAX-RS methods.
Custom Marshalling
So far in this chapter, we've focused on built-in JAX-RS handlers that can marshal and un-
marshal 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
public interface
interface
MessageBodyWriter
MessageBodyWriter
<
T
> {
boolean
boolean
isWriteable
(
Class
<?>
type
,
Type genericType
,
Annotation annotations
[],
MediaType mediaType
);
long
long
getSize
(
T t
,
Class
<?>
type
,
Type genericType
,
Annotation annotations
[],
MediaType mediaType
);
void
void
writeTo
(
T t
,
Class
<?>
type
,
Type genericType
,
Annotation annotations
[],
MediaType mediaType
,
MultivaluedMap
<
String
,
Object
>
httpHeaders
,
OutputStream entityStream
)
throws
throws
IOException
,
WebApplicationException
;
}
The
MessageBodyWriter
interface has only 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
Content-Length