Jax.rs:对象的零长度表示是什么?

时间:2016-12-02 08:06:40

标签: java web-services jax-rs

我有这个问题:

我们有一个像这样的JAX.RS api:

@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("get")
public User get(@QueryParam(value = "id") String identifier) {
    return toUser(getUserEntry(identifier));
}

toUser()方法可以返回null,这实际上意味着客户端将看到204 - No Content响应。

现在,在客户端,我的代码如下所示:

getWebTarget("user")
            .path("get")
            .queryParam("id", identifier)
            .request(getMediaType())
            .get()
            .readEntity(SsoUser.class);

我期待readEntity()抛出某种异常,但它实际上返回null并且不会抱怨。

查看documentation,我看到了这一点:

  

对于零长度响应实体返回表示零长度数据的相应Java对象。 如果没有为Java类型定义零长度表示,则抛出包装底层NoContentException的ProcessingException。

所以看来我的User类确实定义了一个"零长度表示"。但我无法在文档中找到这种表示的含义。

我可以理解Java 可能如何推断出零长度表示为空,但我不知道在哪里定义它。

对此有何见解?

1 个答案:

答案 0 :(得分:-2)

我可能错了,但我不认为Jax-RS能够为你处理null值。你可以做的是明确处理这种情况,例如

@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("get")
public Response get(@QueryParam(value = "id") String identifier) {
    User maybeNull = toUser(getUserEntry(identifier));
    Response response = null;
    if(null == maybeNull) {
      response = Response.noContent().build();
    } else {       
      response = Response.ok(maybeNull).build();
    }
    return response;
}