Search code examples
javajsonrestjerseyjax-rs

Response of a Jersey REST service isn't including null fields


I have this Jersey REST service:

@GET
@Path("/consult")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response consult() {
    Person person = new Person();
    person.setName("Pedro");
    return Response.status(Status.OK).entity(new Gson().toJson(person)).build();
}

.

public class Person {

    private String name;
    private Integer age;
    ...

}

Which gives me this JSON response:

[
  {
    "name": "Pedro"
  }
]

Why the age field isn't included in the JSON response as null? And how can I include it?

[
  {
    "name": "Pedro",
    "age": null
  }
]

EDIT:

I have already tried using @JsonInclude(Include.ALWAYS) like:

@JsonInclude(Include.ALWAYS)
public class Person {

    private String name;
    private Integer age;
    ...

}

But it didn't work for me.


Solution

  • You are using Gson to serialize your object. Gson by default removes null values. To include null values use:

    public Response consult() {
        Gson gson = new GsonBuilder()
            .serializeNulls()
            .create();
        Person person = new Person();
        person.setName("Pedro");
        return Response.status(Status.OK).entity(gson.toJson(person)).build();
    }
    

    More info