3

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.


cgajardo
  • 364
  • 1
  • 2
  • 17

1 Answers1

2
  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;
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • 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 :/ – cgajardo Apr 30 '15 at 11:34
  • I would imagine then that Jackson (at least this version) is not even being used. Please post your project dependencies and please let us know what Server you are using, and also any app configuration (web.xml or Java config) – Paul Samsotha Apr 30 '15 at 11:37
  • My guess is it's something related to [this](http://stackoverflow.com/q/29698350/2587435). But just a guess, Hard to tell without knowing more – Paul Samsotha Apr 30 '15 at 11:40