java - 使用 Jersey 防止对象属性内的空值

标签 java json jersey jackson

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

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

Stat 类看起来像这样:

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

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

我们将不胜感激。


最佳答案

  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;
}

关于java - 使用 Jersey 防止对象属性内的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29954714/

相关文章:

json - Newtonsoft Json 模式

java - JSON数据问题

java - 使用 Application 子类时,Swagger 不显示 Jersey 的 @Api 注释

java - 如何使用 Spring MVC 实现服务 REST (Jersey) 请求和网页请求?

java - derby + hibernate ConstraintViolationException 使用多对多关系

java - spring mvc 声明所有 beans 单例

Javascript:反序列化对象和混合方法

javascript - AngularJS 中的 JSON 解析

java - 在 'for' 循环 java 中重新启动当前迭代

java - Tomcat 6 的 JDBC 池