In this short tutorial, you'll learn how to use the Jackson's @JsonInclude
annotation to ignore null fields while serializing a Java Object to its JSON representation.
By default, Jackson includes null fields when we serialize a Java Object to its JSON representation. For a deeper understanding, let us create a simple User
class:
public class User {
public String name;
public String email;
private String[] roles;
private boolean admin;
public User() {
}
public User(String name, String email, String[] roles, boolean admin) {
this.name = name;
this.email = email;
this.roles = roles;
this.admin = admin;
}
// getters and setters, toString() .... (omitted for brevity)
}
Now let us create an instance of User
and then try to convert it into a JSON string:
try {
// create user object
User user = new User("John Doe", null, null, true);
// convert user object to JSON
String json = new ObjectMapper().writeValueAsString(user);
// print JSON string
System.out.println(json);
} catch (Exception ex) {
ex.printStackTrace();
}
As you can see above, we set the email
and roles
fields to null while creating a new user object. Here is the JSON string generated by the above code:
{"name":"John Doe","email":null,"roles":null,"admin":true}
To remove null fields from the generated JSON, just put @JsonInclude
on the class level, field level, or globally.
Ignore Null Fields on Class Level
To ignore all null fields for a specific class, put the @JsonInclude
annotation on top of the class name:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
// ...
}
Now, if you run the above example code, you should see that no null fields are a part of the final JSON output:
{"name":"John Doe","admin":true}
Ignore Null Fields on Field Level
You can even specify the @JsonInclude
annotation on the field level for more granular control:
public class User {
public String name;
@JsonInclude(JsonInclude.Include.NON_NULL)
public String email;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String[] roles;
private boolean admin;
// ....
}
Ignore Null Fields Globally
Jackson also allows us to configure null fields behavior globally on the ObjectMapper
instance, as shown below:
try {
// create user object
User user = new User("John Doe", null, null, true);
// create object mapper instance
ObjectMapper mapper = new ObjectMapper();
// configure null fields behavior
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// convert user object to JSON
String json = mapper.writeValueAsString(user);
// print JSON string
System.out.println(json);
} catch (Exception ex) {
ex.printStackTrace();
}
Here is the final JSON generated by the above example:
{"name":"John Doe","admin":true}
For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.