Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JacksonProviderProxy writing out null values in json output

Tags:

json

jackson

I have a simple POJO class that extends another simple POJO class. I am using the com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy to marshall the properties in these POJO classes to JSON. However, when I set some of the properties to the POJO as null, then it outputs those properties as the string null instead of not outputting it at all.

for eg.

{
   Person:
   [{
      "firstName":"John"
      "lastName":"null"
    }]
}

instead of:

for eg.

{
   Person:
   [{
      "firstName":"John"
    }]
}
like image 469
Salil Surendran Avatar asked Jul 23 '12 05:07

Salil Surendran


People also ask

How do you ignore null values in JSON response?

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.

How do I ignore null values in JSON response Jackson?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

How do you remove null values from POJO?

Just add @JsonInclude annotation to classes not properties. Tested with and without this and it works.


1 Answers

Different options are available for suppressing serialization of properties with null values, depending on the version of Jackson in use, and whether the ObjectMapper can be directly configured.

With Jackson 1.1+, with direct access to configure the ObjectMapper, you could just call setSerializationInclusion(Include.NON_NULL).

Alternatively, you could annotate the (class) type that has the properties, for which null properties serialization is to be suppressed, with @JsonSerialize(include=Inclusion.NON_NULL).

With Jackson 2+, instead of the @JsonSerialize annotation, use @JsonInclude(Include.NON_NULL).

like image 99
Programmer Bruce Avatar answered Oct 16 '22 15:10

Programmer Bruce