简体   繁体   中英

Exclude empty Arrays from Jackson ObjectMapper

I am building JSON from Java object tree using Jackson ObjectMapper . Some of my Java objects are collections and sometimes they might be empty. So if they are empty that ObjectMapper generates me: "attributes": [], and I want to exclude those kind of empty JSON arrays from my result. My current ObjectMapper config:

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

From this post I've read that I can use:

config.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);

But that is generating 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 prevent those empty arrays to appear in my result?

You should use:

config.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);

for Jackson 1 or

config.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

for Jackson 2

If you can modify the object to be serialized, you can also place an annotation directly on the field, for example (Jackson 2.11.2):

@JsonProperty
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Set<String> mySet = new HashSet<>();

In this way, no further configuration of the ObjectMapper is required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM