简体   繁体   English

泽西休息服务器 - 如果值为0,则排除json响应中的整数

[英]Jersey rest server - Exclude integer in json response if value is 0

Lets say I have this code for creating a person in my rest api. 让我说我有这个代码用于在我的休息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();
}

Example response: 响应示例:

{
    "departmentId" : 0,
    "personId" : 4335,
    "name" : "John Smith"
}

I only want to return the personId and name parameter in the response object. 我只想在响应对象中返回personId和name参数。 How can I in this example exclude the departmentId. 我在这个例子中如何排除departmentId。

Use Integer and as an instance variable it will be null if not set. 使用Integer并将其作为实例变量,如果未设置则为null。 Then your json marshaller will ignore it. 然后你的json marshaller会忽略它。

If you are using Jackson for marshalling, you can use the JsonInclude annotation: 如果您使用Jackson进行编组,则可以使用JsonInclude批注:

@XmlRootElement
public class Person{

  @JsonProperty
  int personId;

  @JsonInclude(Include.NON_DEFAULT)
  @JsonProperty
  int departmentId;

  @JsonProperty
  String name;

}

Using Include.NON_DEFAULT will exclude the property if it's value is 0 (default for int), even if it's a primitive. 如果属性值为0(默认为int),则使用Include.NON_DEFAULT将排除属性,即使它是基元。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM