首页 > 解决方案 > 关联类的 JsonInclude 注释

问题描述

通过在类级别使用 @JsonInclude(JsonInclude.Include.NON_EMPTY) ,它会在序列化过程中忽略空值和空值标签。

是否有任何 JsonInclude 变体或任何其他库或类,我们可以忽略关联(has-a)类的 null 和空属性。

标签: javaspringspring-bootjackson-databindfasterxml

解决方案


您可以选择在类级别使用注释,即:

@JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case 
public static class Request {
  // ...
}

如评论中所述,在 2.x 以下的版本中,此注释的语法为:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) // or JsonSerialize.Inclusion.NON_EMPTY

另一种选择是直接配置 ObjectMapper,只需调用 mapper.setSerializationInclusion(Include.NON_NULL);

正如 draw moore所提到的, 您也许还可以看看Ignore Null Fields with Jackson - Baeldung


推荐阅读