I found that Jersey by default makes use of the Jackson framework for resources to return data in Json format. However, I had the need to use the Gson framework to convert the objects to Json. How to do this if Jersey uses Jackson implicitly?
I found that Jersey by default makes use of the Jackson framework for resources to return data in Json format. However, I had the need to use the Gson framework to convert the objects to Json. How to do this if Jersey uses Jackson implicitly?
Just create a provider class that implements the javax.ws.rs.ext.MessageBodyWriter
interfaces, for serialization of a Java object in Json, and javax.ws.rs.ext.MessageBodyReader
, for deserialization of Json for Java object, and that has @Provider
annotation. Here is an example:
@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public final class GsonMessageBodyHandler implements MessageBodyWriter, MessageBodyReader {
private static final String UTF_8 = "UTF-8";
private Gson gson;
private Gson getGson() {
if (gson == null) {
final GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
}
return gson;
}
@Override
public boolean isReadable(Class type, Type genericType, java.lang.annotation.Annotation[] annotations, MediaType mediaType) {
return true;
}
@Override
public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws Exception, ApplicationException {
InputStreamReader streamReader = new InputStreamReader(entityStream, UTF_8);
try {
Type jsonType;
if (type.equals(genericType)) {
jsonType = type;
} else {
jsonType = genericType;
}
return getGson().fromJson(streamReader, jsonType);
} finally {
streamReader.close();
}
}
@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 httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8);
try {
Type jsonType;
if (type.equals(genericType)) {
jsonType = type;
} else {
jsonType = genericType;
}
getGson().toJson(object, jsonType, writer);
} finally {
writer.close();
}
}
}
Then, in this class we will convert the object format to json format and vice versa, and for this we will use the Gson framework, thus replacing Jackson.Place this class together of your web service resource classes, as well the Jersey will identify it and any Json related conversion will run it.