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

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?

>Solution :

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);

Leave a Reply