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"
}]
}
In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.
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.
Just add @JsonInclude annotation to classes not properties. Tested with and without this and it works.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With