我有这个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() {
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();
}