从Jackson ObjectMapper中排除空数组

6 java json jackson

我正在使用Jackson ObjectMapper从Java对象树构建JSON .我的一些Java对象是集合,有时它们可​​能是空的.因此,如果它们是空的,那么ObjectMapper会生成我:"attributes": [],我想从我的结果中排除那些空的JSON数组.我当前的ObjectMapper配置:

SerializationConfig config = objectMapper.getSerializationConfig();
config.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
config.set(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
Run Code Online (Sandbox Code Playgroud)

从这篇文章我读到我可以使用:

config.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
Run Code Online (Sandbox Code Playgroud)

但这会让我产生错误:

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.
Run Code Online (Sandbox Code Playgroud)

那么我应该如何防止那些空数组出现在我的结果中呢?

jgm*_*jgm 12

你应该使用:

config.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
Run Code Online (Sandbox Code Playgroud)

杰克逊1或

config.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
Run Code Online (Sandbox Code Playgroud)

为杰克逊2