Home > front end >  Ignore null field of a POJO in response
Ignore null field of a POJO in response

Time:05-19

I have a class with few fields

static final class Sample {
     Enum A, B, C, D;
     Sample(A, B, C) {
        // A,B,C init; not D (it's null)
     }
}

When I create an instance of Sample using 3 parameter constructor, I want to ignore 4th one while sending as response to an API call.

How can I achieve this? I can't use JsonIgnore because in other flow, D will have some non null values;

CodePudding user response:

You can ignore null fields at the class level by using @JsonInclude(Include.NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null.

CodePudding user response:

You have to add @JsonInclude(JsonInclude.Include.NON_NULL) of (com.fasterxml.jackson.annotation.JsonInclude;) on class level as below:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
class Sample {
     Enum A, B, C, D;
     Sample(A, B, C) {
        // A,B,C init; not D (it's null)
     }
}
  • Related