sjallamander
sjallamander

Reputation: 439

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.

Upvotes: 2

Views: 2541

Answers (2)

JanneK
JanneK

Reputation: 892

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.

Upvotes: 3

arisalexis
arisalexis

Reputation: 2210

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

Upvotes: 2

Related Questions