Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent null values inside object property using jersey

I'm using jersey to serialize responses in a web service. 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:

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

I don't want properties from Stat to be shown if they are null. But for some reason I keep getting those. I've tried using @JsonInclude(Include.NON_NULL) in Stat class, but it doesn't work :(

Any help will be appreciated.


like image 335
cgajardo Avatar asked Apr 26 '26 13:04

cgajardo


1 Answers

  1. Primitives can't be null. They have default values (int being 0). Instead use the Integer wrapper.

  2. The @JsonInclude(Include.NON_NULL) should be on the Stat class. 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;
}
like image 182
Paul Samsotha Avatar answered Apr 28 '26 02:04

Paul Samsotha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!