by Uwe B. Meding

Using JSON in a Java REST application is pretty straight forward. Jersey is the reference implementation for JAX-RS which does all the serialization for you. The really great part is that if you need more control over this process, you can replace the JSON generation mechanism. All you need is to implement the MessageBodyReader and MessageBodyWriter from the JAVA web-services interface and provide an annotation to indicate your local JSON provider:

@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public final class GsonProvider implements MessageBodyWriter<Object>, MessageBodyReader<Object> {

    private final Gson gson = new GsonBuilder().create();

    // ===== Implement the message writer
    @Override
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return true;
    }

    @Override
    public long getSize(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations,
            MediaType mediaType, MultivaluedMap<String, Object> httpHeaders,
            OutputStream entityStream) throws IOException, WebApplicationException {

        try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, "UTF-8")) {
            gson.toJson(object, genericType, writer);
        }
    }

    // ===== Implement the message body reader
    @Override
    public boolean isReadable(Class<?> type, Type genericType, java.lang.annotation.Annotation[] annotations, MediaType mediaType) {
        return true;
    }

    @Override
    public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations,
            MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
            InputStream entityStream) throws IOException, WebApplicationException {

        try (InputStreamReader streamReader = new InputStreamReader(entityStream, "UTF-8")) {
            return gson.fromJson(streamReader, genericType);
        }
    }
}

Leave a Reply