【问题标题】:Prevent null values inside object property using jersey使用球衣防止对象属性内的空值
【发布时间】:2015-07-09 09:17:29
【问题描述】:

我正在使用 jersey 序列化 Web 服务中的响应。 我不希望服务返回空值,所以我使用相应的注释,如下所示:

@JsonInclude(Include.NON_NULL)    
class City{
   String name;
   Stat stats;  
}

Stat 类看起来像这样:

class Stat{
   int population;
   int femalePopulation;
   int malePopulation;
}

如果 Stat 的属性为空,我不希望显示它们。但出于某种原因,我不断得到那些。我试过在Stat 类中使用@JsonInclude(Include.NON_NULL),但它不起作用:(

任何帮助将不胜感激。


编辑:

抱歉,我的例子不是最好的。我知道原语类型有默认值。我已经尝试在 Stat 类中添加注释,但它对我来说不起作用:/

class Stat{
   Integer population;
   Integer femalePopulation;
   Integer malePopulation;
}

【问题讨论】:

    标签: java json jersey jackson


    【解决方案1】:
    1. 基元不能为空。它们具有默认值(int 为 0)。而是使用 Integer 包装器。

    2. @JsonInclude(Include.NON_NULL) 应该在 Stat 类上。如果可能的话,我不确定如何递归地包含它。

    所以只需执行以下操作,它应该可以工作(经过测试)

    @JsonInclude(Include.NON_NULL) 
    public class Stat {
    
        public Integer population;
        public Integer femalePopulation;
        public Integer malePopulation;
    }
    

    【讨论】:

    • 对不起,我的例子不是最好的。我知道原语类型有默认值。我已经尝试在 Stat 类中添加注释,但它对我来说不起作用:/
    • 我想那时杰克逊(至少这个版本)甚至没有被使用。请发布您的项目依赖项,并让我们知道您使用的是什么服务器,以及任何应用程序配置(web.xml 或 Java 配置)
    • 我猜它与this 有关。但只是一个猜测,不知道更多就很难说
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 2017-08-30
    • 2019-01-13
    • 1970-01-01
    相关资源
    最近更新 更多