#TechBite: Jackson @JsonInclude with NON_EMPTY

Etimbuk U
2 min readJan 12, 2020

--

Serializing only fields with values

It’s the first #TechBite of 2020 😃.

Hopefully, you all had a lovely Christmas and New year break.

So let us get straight to it…

@JsonInclude. What is it? 🤔

According to the documentation

Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all 
properties of the annotated class, is to be serialized.
Without annotation property values are always included, but by using
this annotation one can specify simple exclusion rules to reduce
amount of properties to write out.

When can we use it?

The first statement in the documentation says it all but for emphasis,

Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all properties of the annotated class, is to be serialized.

In summary, we can use to include null, empty, null and/or empty value(s) to the result of a serialized object.

So what does NON_EMPTY have to do with JSONInclude? 🤔 🤔

As it is with annotations, they usually accept parameters. NON_EMPTY is one of the values for the JsonInclude value parameter.

Oh okay! 🙄 So what does NON_EMPTY (Include.NON_EMPTY) do? 🤔

Value that indicates that only properties with null value,
or what is considered empty, are not to be included.
Definition of emptiness is data type specific; see below
for details on actual handling.

So any example(s)? 💭

Sure, we have examples. To illustrate this, we will

  • have a simple Person class that has-an Address

In the above Person and Address classes, we have added the @JsonInclude(JsonInclude.Include.NON_EMPTY) annotation.

Next, we will add a few test scenarios to verify this annotation does what it says it does 😃

Above test scenario tests with an empty firstname for a Person. And this results in a JSON which does not include the firstname property once serialized.

Now, what will our result serialized Person be when we pass in an empty Person object? We get an empty JSON as shown in our below test scenario.

And this wraps it on this week’s #TechBite. The code can be found here.

--

--

Etimbuk U

Java | Flutter | Android | Some JavaScript | API Design