Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

@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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading