【问题标题】:Exclude 0 from JSON response in Jackson Spring boot在 Jackson Spring 启动中从 JSON 响应中排除 0
【发布时间】:2021-06-09 10:10:03
【问题描述】:

我有一个这样的 POJO。

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Test {

    private int a;

    private String b;
}

如果属性“a”的值为 0,我想排除它。字符串 b 被排除在

@JsonInclude(JsonInclude.Include.NON_NULL)

我唯一能做的就是将 int 数据类型转换为 Integer Object,如果它是 0,则在 setter 中将值显式设置为 NULL。

任何其他建议或正确的解决方案将不胜感激

【问题讨论】:

  • 我认为您将int 更改为Integer 的方式是正确的,因为原始类型具有默认值(在这种情况下0 用于int 字段)和0(如@ 987654329@) 无法与null 进行比较。
  • 但这是另一个可能有帮助的解决方案:stackoverflow.com/a/45353643/2201165

标签: spring-boot jackson


【解决方案1】:

选项 1:

照你说的做:将int 更改为Integer 并使用@JsonInclude(Include.NON_NULL)。因为原始类型具有默认值并且它们的值不能与null 进行比较,所以您必须将int 包装到Integer。见Primitive Data Types。恕我直言,这是更清洁的方式。

选项 2

使用此answer 中描述的方式并改用@JsonInclude(Include.NON_DEFAULT)(请参阅Jackson-annotations API),以便忽略默认值(以及对象的null 值)。


注意

如果您只想排除特定字段(在您的情况下是 int/Integer - a - 字段)当它具有 null-/default 值和其他字段(在您的情况下String - b - 字段)应在具有null-/默认值时包含在内,将注释放在字段级别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 2019-12-05
    • 2016-09-24
    • 2019-01-13
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多