Avatar ·

How to make Jackson ignore null fields when serializing to JSON?

Hello everyone! I'm just starting to learn Jackson for working with JSON in Java, and I've encountered a problem. I have a User class with several fields, some of which can be null. When I serialize an object to JSON, Jackson by default includes these null fields, which clutters the output. For example:

\n\n
public class User {\n    private String name;\n    private String email;\n    private String phone;\n    // getters and setters\n}\n\nUser user = new User();\nuser.setName("Ivan");\n// email and phone are not set, they are null\n\nObjectMapper mapper = new ObjectMapper();\nString json = mapper.writeValueAsString(user);\n// Result: {"name":"Ivan","email":null,"phone":null}\n
\n\n

I need fields with null values to simply not be included