Jersey response.readEntity(...) 有时返回 null

问题描述 投票:0回答:1

考虑我的 REST 客户端 (Jersey 2.26) 中的这段代码。它用于发布对象并返回响应对象。如果 REST 服务器返回错误(状态 >= 400),那么我不想返回

T
类型的实体,而是想读取
ErrorMessage
类型的实体并抛出包含错误消息对象的异常。

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;
}

如果没有发生错误(状态< 400), then my object of type

T
按预期返回。但是,当发生错误时,
response.readEntity(ErrorMessage.class)
返回
null
。但是(这是奇怪的部分),这确实获取了我的数据(在
handleErrors
方法):

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

我可以使用它并手动反序列化它..但我首先想知道是否有任何选项可以在不实施解决方法的情况下修复此问题。

jackson jersey jax-rs json-deserialization
1个回答
1
投票

从默认的 MOXy JSON(反)序列化器切换后(我们现在使用 GSON 提供程序),问题得到了解决。

我们最近在 JSON-B 上遇到了类似的问题。事实证明,我们必须在错误对象上添加 getter 和 setter 才能(反)序列化该对象。

© www.soinside.com 2019 - 2024. All rights reserved.