jacksonjerseyjax-rsjson-deserialization

Jersey response.readEntity(...) sometimes returns null


Consider this snippet from my REST client (Jersey 2.26). It's used to post objects and return the response object. If the REST server returns an error (status >= 400), then instead of returning an entity of type T I want to read an entity of type ErrorMessage and throw an exception containing the error message object.

protected <T> T post(final Class<T> type,
                     final Object entity,
                     final Map<String, Object> queryParams,
                     final String methodPath,
                     final Object... arguments) {
  return postResponse(
    getInvocationBuilderJson(methodPath,
                             queryParams,
                             arguments),
    entity
  ).readEntity(type);
}

protected Response postResponse(final Invocation.Builder invocationBuilder,
                                final Object entity) {
  return handleErrors(
    invocationBuilder.post(Entity.entity(entity,
                                         MediaType.APPLICATION_JSON_TYPE))
  );
}

protected Response handleErrors(final Response response) {
  if (response.getStatus() >= 400) {
    throw new InvocationException(response.readEntity(ErrorMessage.class));
  }
  return response;
}

If no error occurs (status < 400), then my object of type T is returned as expected. However, when an error does occur, response.readEntity(ErrorMessage.class) returns null. But (and this is the strange part), this does get me data (at the handleErrors method):

byte[] data = readAllBytes((InputStream) response.getEntity());

I could use that and deserialize it manually.. but I would first like to know if there are any options to fix this without implementing workarounds.


Solution

  • After switching from the default MOXy JSON (de)serializer (we now are using a GSON provider) the problem was resolved.

    We recently had a similar issue with JSON-B. There is turned out we had to add a getter and setter on our error object in order to (de)serialize the object.