@Jsoninclude(Include. Non_Null) Not Working as Expected

@Jsoninclude(Include. Non_Null) Not Working as Expected

I have added @JsonInclude(Include.NON_NULL) annotation on Response class.

@JsonInclude(Include.NON_NULL)
public class Response {

  @JsonProperty
  private String message;

 // getter-setters
}

If the value is null the property does not include in JSON

But still I am getting this property as a NULL.

{
"message": null
}

What can be the reason ? Am I missing anything ?

1

5 Answers

I tried

@JsonSerialize(include = Inclusion.NON_NULL)

intead of

@JsonInclude(Include.NON_NULL)

and it worked as expected.

5

This is the correct way of using it. This I valid from jdk 8 +.

@JsonInclude(JsonInclude.Include.NON_EMPTY)

more information is available in : json-include-non-empty

This has been deprecated:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)

Use instead:

@JsonInclude(Include.NON_NULL)
0

I am using Java Spring & in that, I am implementing like :

Class Level:

import com.fasterxml.jackson.annotation.JsonInclude;

        @JsonInclude(JsonInclude.Include.NON_NULL)
        public class Student {

            String name;
            //getter-setter
    }

You can also implement it on elements level of class :

Elements Level:

import com.fasterxml.jackson.annotation.JsonInclude;

        @JsonInclude(JsonInclude.Include.NON_NULL)
        public class Student {

            String name;

            @JsonInclude(JsonInclude.Include.NON_NULL)
            String address;
            //getter-setter
    }
1

I encountered the same issue Solved by using

@JsonInclude(value = Include.NON_EMPTY, content = Include.NON_NULL)
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.