@JsonInclude(Include.NON_NULL) not working as expected

@JsonInclude(Include.NON_NULL) not working as expected

Problem Description:

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 ?

Solution – 1

I tried

@JsonSerialize(include = Inclusion.NON_NULL)

intead of

@JsonInclude(Include.NON_NULL)

and it worked as expected.

Solution – 2

This is deprecated:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)

Instead use:

@JsonInclude(Include.NON_NULL)

Solution – 3

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
    }

Solution – 4

I encountered the same issue
Solved by using

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

Solution – 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

Solution – 6

Add @JsonInclude(JsonInclude.Include.NON_NULL) at the attribute level instead of class level as show below :

public class Response {
  @JsonInclude(JsonInclude.Include.NON_NULL)
  private String message;
  // getters and setters
}

You can also change your class to record and add the json property then you don’t have to write the getters and setters:

public record Response(@JsonInclude(JsonInclude.Include.NON_NULL) String message) {}
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject