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

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

我有这个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;
    ...

}

但是它对我不起作用。

java json rest jersey jax-rs
2个回答
0
投票

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


0
投票

您正在使用Gson序列化对象。默认情况下,Gson会删除空值。要包含空值,请使用:

public Response consult() {
    GsonBuilder gsonBuilder = new GsonBuilder();  
    gsonBuilder.serializeNulls();  
    Gson gson = gsonBuilder.create();
    Person person = new Person();
    person.setName("Pedro");
    return Response.status(Status.OK).entity(gson.toJson(person)).build();
}
© www.soinside.com 2019 - 2024. All rights reserved.