@JsonInclude(JsonInclude.Include.NON_NULL) is not working with Lombok

Viewed 22

I have a code in class:

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiModels {

    private String address;
    private String age;
    private String name; 
}

When i'm trying to set only address:

public class TestClass {
    ApiModels models = new ApiModels();
    @Test
    void someMethod() {

        models.setAddress("Some address");

        System.out.println(models);
    }
}

I see all this output:

ApiModels(address=Some address, age=null, name=null)

But i don't need null values. How can i fix it?

2 Answers

You are printing object as String not the serialized Json. If you serialize object to Json then it will not show null fields. To see the use of @Jsoninclude(JsonInclude.Include.NON_NULL) check the following code.

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

ApiModels apm = new ApiModels('no: 23','12',NULL);
String serializedAPM = mapper.writeValueAsString(apm);
System.out.println(serializedAPM);

System.out.println(models) will invoke the .toString() and show you the results. None of this is JSON related - @JsonInclude and co are relevant when you ask the json serializer to serialize your object. At which point, the null values will not be sent.

Lombok is generating your toString method in your snippet. It cannot be told to 'skip' null values and you probably don't want to: toString() output is solely for debugging, any structured string data (such as a JSON dump of your object) should be done via other methods.

Related