我正在使用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);
从this post我已经读过我可以使用:
config.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
但这会让我产生错误:
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.
那么我应该如何防止那些空数组出现在我的结果中呢?
答案 0 :(得分:12)
您应该使用:
config.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
杰克逊1或
config.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
杰克逊2
答案 1 :(得分:0)
如果您可以修改要序列化的对象,则还可以直接在字段上放置注释,例如(Jackson 2.11.2):
@JsonProperty
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Set<String> mySet = new HashSet<>();
通过这种方式,无需进一步配置ObjectMapper
。