Java Jersey rest server-如果值为0,则在json响应中排除整数
假设我有一段代码,用于在RESTAPI中创建一个人Java Jersey rest server-如果值为0,则在json响应中排除整数,java,rest,jersey,Java,Rest,Jersey,假设我有一段代码,用于在RESTAPI中创建一个人 @XmlRootElement public class Person { int personId, departmentId; String name; } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response create(Person person) { cre
@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。使用Integer,如果不设置,它作为实例变量将为null。然后json封送器将忽略它。如果您使用Jackson进行封送,可以使用JsonInclude注释:
@XmlRootElement
public class Person{
@JsonProperty
int personId;
@JsonInclude(Include.NON_DEFAULT)
@JsonProperty
int departmentId;
@JsonProperty
String name;
}
如果属性的值为0(int的默认值),则使用Include.NON_DEFAULT将排除该属性,即使它是一个基元。这取决于封送拆收器。如果是Jackson,则应另外使用
@JsonInclude(Include.NON_NULL)
注释Person
,以使其完全忽略属性,而不是返回NULL。