简体   繁体   English

使用jersey防止对象属性内的空值

[英]Prevent null values inside object property using jersey

I'm using jersey to serialize responses in a web service. 我正在使用运动衫来序列化Web服务中的响应。 I don't want the service to return null values, so i use the corresponding annotation, like this: 我不希望服务返回空值,所以我使用相应的注释,如下所示:

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

And Stat class looks like this: Stat类看起来像这样:

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

I don't want properties from Stat to be shown if they are null. 如果它们为null,我不希望显示Stat的属性。 But for some reason I keep getting those. 但出于某种原因,我一直在那些。 I've tried using @JsonInclude(Include.NON_NULL) in Stat class, but it doesn't work :( 我曾尝试在Stat类中使用@JsonInclude(Include.NON_NULL) ,但它不起作用:(

Any help will be appreciated. 任何帮助将不胜感激。


EDIT: 编辑:

Sorry, my example wasn't the best one. 对不起,我的例子不是最好的。 I know primitives types have default values. 我知道基元类型有默认值。 I've tried adding the annotation in Stat class, but it's not woking for me :/ 我已经尝试在Stat类中添加注释,但它并不是为了我:

class Stat{
   Integer population;
   Integer femalePopulation;
   Integer malePopulation;
}
  1. Primitives can't be null. 基元不能为空。 They have default values (int being 0). 它们具有默认值(int为0)。 Instead use the Integer wrapper. 而是使用Integer包装器。

  2. The @JsonInclude(Include.NON_NULL) should be on the Stat class. @JsonInclude(Include.NON_NULL)应该在Stat类上。 I am not sure how to include it recursively, if that's even possible. 如果可能的话,我不知道如何递归地包含它。

So just do the following, and it should work (as tested) 所以,只需执行以下操作,它应该工作(如测试)

@JsonInclude(Include.NON_NULL) 
public class Stat {

    public Integer population;
    public Integer femalePopulation;
    public Integer malePopulation;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 java object 中搜索 null 值? - How to search for null values inside a java object? 如何防止 Map 中的空值和 bean 中的空字段通过 Jackson 序列化 - How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson Jersey将null值序列化为json:如何跳过 - Jersey serializing null values to json : How to skip Jersey POST方法接收空值作为参数 - Jersey POST Method is receiving null values as parameters 使用泽西和弹簧在REST服务上的空指针 - Null pointer on service in REST using jersey and spring 将Spring属性占位符与Jersey @Path和@ApplicationPath一起使用 - Using Spring property placeholders with Jersey @Path and @ApplicationPath 使用 Java 将列表 object 中的属性断言为 null 8 - Assert a property from list object as null using Java 8 使用对象映射器反序列化具有 null 作为值的属性 - Deserialize a property which is having null as a value using object mapper Jersey POST参数值始终为null,但可与curl命令配合使用 - Jersey POST parameter values always null, but works fine with curl command Jersey 1.x正在将我的序列化null字段解释为值为“ null”的字符串。 我该如何预防? - Jersey 1.x is interpreting my serialized null fields as Strings with the value of “null”. How do I prevent this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM