0

Below is the sample class :

import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Data
@JsonInclude(Include.NON_NULL)
public class SpouseRes implements Serializable  {

    private static final long serialVersionUID = 7830471917333093173L;
    
    //This object is used to check if the object is empty or not (all data members are null)
    @JsonIgnore
    private static final SpouseRes EMPTY = new SpouseRes();

    @JsonInclude(Include.NON_DEFAULT)
    @JsonProperty("age")
    private Integer age;
    
    @JsonProperty("salary")
    private SalaryResponse salary;
    
    // Function to check if the current object is empty
    @JsonIgnore
    public boolean isEmpty() {
        return this.equals(EMPTY);
    }
}

When getting this object from response, this is empty and the data member is getting set to 0. Thats why its not getting detected as empty in Object.isEmpty(). Below is the setter code :

        // Setting spouse salary
        SpouseRes spouse = new SpouseRes();

        // Check if Retirement age is null or default value 0
        if(Client.getSpouseRetireAge() != 0 || Client.getSpouseRetireAge() != null) {
            spouse.setRetireAge(Client.getSpouseRetireAge());
        }
        else {
            spouse.setRetireAge(null);  
        }

The JSON output is :

  "client": {
                  "displayName": "Tony",
                  "age": 14,
                  "retirementAge": 90,
                  "salary": {
                  "amount": 0.0
                   },
                   "spouse": {}
            }

So, after using all of these, still getting this empty Object in JSON response, How to remove this ?

1 Answer 1

1

In order to exclude and empty object in response you will have to annotate your class with:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
Sign up to request clarification or add additional context in comments.

2 Comments

Didn't worked bro, I think I should change the OR condition to AND to make the default value of Integer(0) to NULL explicitly. As the object is not empty, one of its data member is set to default value 0 when I use 'new' keyword. So it wouldn't be detected as empty.
hmm. yea that should be a work around.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.