如何使用 Java 中的 Jackson 库忽略 null 和空字段?\
javajsonobject oriented programmingprogramming更新于 2025/7/14 0:12:17
Jackson 是一个 Java 库,它具有非常强大的数据绑定功能,并提供了一个框架来将自定义 Java 对象序列化为 JSON 和将 JSON 反序列化回 Java 对象。 Jackson 库提供了 @JsonInclude 注释,用于根据序列化过程中的值控制整个类或其各个字段的序列化。
@JsonInclude 注释包含以下两个值
- Include.NON_NULL:表示只有非空值的属性才会包含在 JSON 中。
- Include.NON_EMPTY:表示只有非空的属性才会包含在 JSON 中
示例
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
public class IgnoreNullAndEmptyFieldTest {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Employee employee = new Employee(115, null, ""); // 传递 null 和空字段
String result = mapper.writeValueAsString(employee);
System.out.println(result);
}
}
// Employee class
class Employee {
private int id;
@JsonInclude(Include.NON_NULL)
private String firstName;
@JsonInclude(Include.NON_EMPTY) private String lastName;
public Employee(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
输出
{
"id" : 115
}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

