Exclude empty arrays from Jackson ObjectMapper

I am creating JSON from the Java object tree using Jackson ObjectMapper . Some of my Java objects are collections, and sometimes they can be empty. Therefore, if they are empty, that ObjectMapper generates me: "attributes": [],and I want to exclude such empty JSON arrays from this result. My current ObjectMapper configuration:

SerializationConfig config = objectMapper.getSerializationConfig();
config.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
config.set(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);

From this post I read that I can use:

config.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);

But this gives me an error:

Caused by: java.lang.IllegalArgumentException: Class com.mycomp.assessments.evaluation.EvaluationImpl$1 has no default constructor; can not instantiate default bean value to support 'properties=JsonSerialize.Inclusion.NON_DEFAULT' annotation.

So, how should I put these empty arrays in my result?

+5
source share
1 answer

You should use:

config.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);

for jackson 1 or

config.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

for jackson 2

+9
source

All Articles