假设我有这段代码用于在我的 REST API 中创建一个人。
@XmlRootElement
public class Person
{
int personId, departmentId;
String name;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response create(Person person)
{
createPerson(person);
Person p = new Person();
p.setPersonId(p.getPersonId());
p.setName(p.getName());
return Response.status(Response.Status.CREATED).entity(p).build();
}
响应示例:
{
"departmentId" : 0,
"personId" : 4335,
"name" : "John Smith"
}
我只想返回响应对象中的 personId 和 name 参数。在这个例子中我怎样才能排除departmentId。
最佳答案
如果您使用 Jackson 进行编码,则可以使用 JsonIninclude 注释:
@XmlRootElement
public class Person{
@JsonProperty
int personId;
@JsonInclude(Include.NON_DEFAULT)
@JsonProperty
int departmentId;
@JsonProperty
String name;
}
如果属性值为 0(默认为 int),则使用 Include.NON_DEFAULT 将排除该属性,即使它是基元。
关于java - Jersey 休息服务器 - 如果值为 0,则排除 json 响应中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862110/