Java Reference
In-Depth Information
9.5.4. Using a JsonBuilder to control the output
To customize output generation, JAX-RS includes an interface called
javax.ws.rs.ext .MessageBodyWriter<T> . This interface is the contract for
converting a Java type into a stream. It contains three methods to be implemented.
The first method is called isWriteable , and it returns true for types supported by this
writer. For the Person class the implementation is simple:
boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
type == Person && mediaType == MediaType.APPLICATION_JSON_TYPE
}
The method returns true only for Person instances and only if the specified media type is
JSON.
The second method is called getSize , and it's deprecated in JAX-RS 2.0. Its implement-
ation is supposed to return -1:
long getSize(Person t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
The writeTo method does all the work. Here I use groovy.json.JsonBuilder to
generate the output in the form I want, as shown in the following listing.
Search WWH ::




Custom Search