简体   繁体   中英

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.

@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. How can I in this example exclude the departmentId.

Use Integer and as an instance variable it will be null if not set. Then your json marshaller will ignore it.

If you are using Jackson for marshalling, you can use the JsonInclude annotation:

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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