在许多情况下,返回的 JSON 数据可能包含许多 null 值的字段,这会导致数据冗余,增加网络传输的负担,并使得前端处理数据变得复杂。因此,使用 @JsonInclude(JsonInclude.Include.NON_NULL) 可以帮助我们优化 JSON 的输出,用于控制在序列化过程中是否包含 null 值的字段,确保只返回有效的数据。
考虑以下响应对象定义:
import com.fasterxml.jackson.annotation.JsonInclude;
public class User {
private String name;
private Integer age;
private String email;
private String address;
private String phone;
private String occupation;
private String hobby;
private String bio;
private String gender;
private String nationality;
private Boolean married;
private Integer children;
private Double salary;
// Getters and Setters
}
//赋值伪代码
User user = new User();
user.setName("Alice");
user.setAge(28);
user.setEmail(null);
user.setAddress("");
user.setPhone("123-456-7890");
user.setOccupation(null);
user.setHobby("reading");
user.setBio("");
user.setGender(null);
user.setNationality("");
user.setMarried(null);
user.setChildren(null);
user.setSalary(null);
当我们将这个对象序列化为 JSON 时,由于没有使用 @JsonInclude 注解,生成的 JSON 将是:
{
"name": "Alice",
"age": 28,
"email": null,
"address": "",
"phone": "123-456-7890",
"occupation": null,
"hobby": "reading",
"bio": "",
"gender": null,
"nationality": "",
"married": null,
"children": null,
"salary": null
}
在没有使用 @JsonInclude(JsonInclude.Include.NON_NULL) 的情况下,返回的 JSON 数据包含了大量的 null 值字段:
email、occupation、gender、married、children、salary 等字段的值均为 null,这使得数据显得冗余。
空字符串字段(如 address 和 bio)虽然仍然存在,但它们的存在与否可能并不重要。
相比之下,使用 @JsonInclude(JsonInclude.Include.NON_NULL) 后,生成的 JSON 数据会更为简洁:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
private String name;
private Integer age;
private String email;
private String address;
private String phone;
private String occupation;
private String hobby;
private String bio;
private String gender;
private String nationality;
private Boolean married;
private Integer children;
private Double salary;
// Getters and Setters
}
响应给前端:
{
"name": "Alice",
"age": 28,
"address": "",
"phone": "123-456-7890",
"hobby": "reading",
"bio": ""
}