Jersey REST 服务的响应不包括空字段

Response of a Jersey REST service isn't including null fields

我有这个 Jersey REST 服务:

@GET
@Path("/consult")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response consult() {
    Person person = new Person();
    person.setName("Pedro");
    return Response.status(Status.OK).entity(new Gson().toJson(person)).build();
}

.

public class Person {

    private String name;
    private Integer age;
    ...

}

这给了我这个 JSON 响应:

[
  {
    "name": "Pedro"
  }
]

为什么 age 字段没有作为 null 包含在 JSON 响应中?我怎样才能包含它?

[
  {
    "name": "Pedro",
    "age": null
  }
]

编辑:

我已经尝试使用 @JsonInclude(Include.ALWAYS) 像:

@JsonInclude(Include.ALWAYS)
public class Person {

    private String name;
    private Integer age;
    ...

}

但它对我不起作用。

使用此注释应该可以解决您的问题 @JsonInclude(Include.ALWAYS)

您正在使用 Gson 序列化您的对象。 Gson 默认移除空值。要包含空值,请使用:

public Response consult() {
    Gson gson = new GsonBuilder()
        .serializeNulls()
        .create();
    Person person = new Person();
    person.setName("Pedro");
    return Response.status(Status.OK).entity(gson.toJson(person)).build();
}

More info

谁 'include' 表示它是 GSON 库。 您可以使用 GsonBuilder 创建一个 gson 实例,您可以像这样配置您的 gson 解析器:

class .... {
  static Gson gson = new GsonBuilder()
        .setPrettyPrinting() // build json formatted (optional)
        .serializeNulls() // include null fields
        .create();

那你就用gson

return Response.status(Status.OK).entity(gson.toJson(person)).build();