Jackson - @JsonInclude之NON_DEFAULT

@JsonInclude(JsonInclude.Include.NON_DEFAULT)可用于排除具有POJO默认值的属性。这有不同的用法,如下所示:

  • 如果在类级别使用@JsonInclude(JsonInclude.Include.NON_DEFAULT),则将排除字段的默认值。这是通过使用零参数构造函数创建POJO实例并比较属性值(不包括默认值,例如,默认int值为0,默认String值为null等)来完成的。
  • 如果在属性级别使用@JsonInclude(JsonInclude.Include.NON_DEFAULT)或使用:ObjectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);在两种情况下:
    • 所有被视为“空”的值(根据NON_EMPTY) 被排除在外
    • 原始/包装默认值被排除
    • 排除毫秒值为“ 0L”的日期/时间值
例子
Java对象
在Class上使用NON_DEFAULT
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public class Employee {
     private String name;
     private String dept;
     private Integer salary;
     private boolean fullTime;
     private List<String> phones;
     private Date dateOfBirth;
}
public class ExampleMain {
    public static void main(String[] args) throws IOException {
        Employee employee = new Employee();
        employee.setName("Trish");
        employee.setFullTime(false);
        employee.setPhones(new ArrayList<>());
        employee.setSalary(Integer.valueOf(0));
        employee.setDateOfBirth(new Date(0));

        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(employee);
        System.out.println(jsonString);
    }
}
结果
{"name":"Trish","salary":0,"phones":[],"dateOfBirth":0}

从上面的输出中可以看出,只有具有默认成员值的属性被排除。不排除带0的整数(原始包装器 - salary),不排除带0毫秒的日期,也不排除“空”收集(phones)。

在属性上使用NON_DEFAULT
public class Employee2 {
    @JsonInclude(JsonInclude.Include.NON_DEFAULT)
    private String name;
    @JsonInclude(JsonInclude.Include.NON_DEFAULT)
    private String dept;
    @JsonInclude(JsonInclude.Include.NON_DEFAULT)
    private Integer salary;
    @JsonInclude(JsonInclude.Include.NON_DEFAULT)
    private boolean fullTime;
    @JsonInclude(JsonInclude.Include.NON_DEFAULT)
    private List<String> phones;
    @JsonInclude(JsonInclude.Include.NON_DEFAULT)
    private Date dateOfBirth;
}
public class ExampleMain2 {
    public static void main(String[] args) throws IOException {
        Employee2 employee = new Employee2();
        employee.setName("Trish");
        employee.setFullTime(false);
        employee.setPhones(new ArrayList<>());
        employee.setSalary(Integer.valueOf(0));
        employee.setDateOfBirth(new Date(0));

        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(employee);
        System.out.println(jsonString);
    }
}
结果
{"name":"Trish"}
全局使用NON_DEFAULT
public class ExampleMain3 {
    public static void main(String[] args) throws IOException {
        Employee2 employee = new Employee2();
        employee.setName("Trish");
        employee.setFullTime(false);
        employee.setPhones(new ArrayList<>());
        employee.setSalary(Integer.valueOf(0));
        employee.setDateOfBirth(new Date(0));

        ObjectMapper om = new ObjectMapper();
        om.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);
        String jsonString = om.writeValueAsString(employee);
        System.out.println(jsonString);
    }
}
结果
{"name":"Trish"}

如上所示,最后两个选项产生了相同的结果,即“空”值,原始/包装器默认值和具有0L毫秒的日期也被排除在外。

`@JsonInclude(JsonInclude.Include.NON_EMPTY)` 是 Jackson 提供的一个注解,用于控制 **序列化 Java 对象为 JSON 时字段的包含策略**。它可以让你**只序列化非空(non-empty)的字段**,从而避免 JSON 输出中出现 `null`、空字符串、空数组等无意义的字段。 --- ## ✅ `@JsonInclude(JsonInclude.Include.NON_EMPTY)` 的作用 ### ✅ 适用范围 它可以作用在: - **类级别(Class Level)**:对类中所有字段生效 - **字段级别(Field Level)**:仅对某个字段生效 - **getter 方法上** ### ✅ 包含规则(Include Rules) `JsonInclude.Include.NON_EMPTY` 的含义是: | 类型 | 是否序列化 | |------|-------------| | `null` | ❌ 不序列化 | | 空字符串 `""` | ❌ 不序列化 | | 空集合 `List`, `Map` 等 | ❌ 不序列化 | | 空数组 `[]` | ❌ 不序列化 | | `0`, `false` | ✅ 会序列化 | | 非空字符串、非空对象等 | ✅ 会序列化 | --- ## ✅ 示例代码 ### Java 实体类 ```java import com.fasterxml.jackson.annotation.JsonInclude; import java.util.ArrayList; import java.util.Date; import java.util.List; @JsonInclude(JsonInclude.Include.NON_EMPTY) // 类级别设置 public class User { private String username; private String password; private String email; private Integer age; private List<String> roles = new ArrayList<>(); private Date birthDate; // Getter 和 Setter } ``` ### 测试代码 ```java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Test { public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); User user = new User(); user.setUsername("john"); user.setPassword(""); // 空字符串 user.setEmail(null); // null user.setAge(0); // 0 会被序列化 user.setBirthDate(new Date()); String json = mapper.writeValueAsString(user); System.out.println(json); } } ``` ### 输出结果 ```json {"username":"john","age":0,"birthDate":"2025-04-05T12:34:56.789+0000"} ``` 可以看到: - `password` 是空字符串,未被序列化 - `email` 是 `null`,未被序列化 - `roles` 是空集合,未被序列化 - `username`、`age`、`birthDate` 是非空值,被序列化了 --- ## ✅ `@JsonInclude` 的其他选项 | 选项 | 说明 | |------|------| | `@JsonInclude(JsonInclude.Include.ALWAYS)` | 默认值,所有字段都序列化 | | `@JsonInclude(JsonInclude.Include.NON_NULL)` | 只序列化非 null 的字段 | | `@JsonInclude(JsonInclude.Include.NON_EMPTY)` | 序列化非 null 且非空值(空字符串、空集合等不序列化) | | `@JsonInclude(JsonInclude.Include.NON_DEFAULT)` | 序列化非默认值(如 int 0、boolean false 不序列化) | | `@JsonInclude(JsonInclude.Include.CUSTOM)` | 自定义过滤规则 | --- ## ✅ 和 `@JsonIgnore` 的区别 | 注解 | 行为 | |------|------| | `@JsonIgnore` | 完全忽略字段(无论是否为 null 或空值) | | `@JsonInclude(...)` | 根据字段值是否为 null 或空来决定是否序列化 | --- ## ✅ 全局配置(可选) 你也可以在 `ObjectMapper` 中设置全局的序列化规则,而不需要在每个类上加注解: ```java ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); ``` --- ## ✅ 使用场景 | 场景 | 说明 | |------|------| | 接口返回 JSON 数据 | 避免返回 `null` 字段,提升可读性 | | 敏感字段处理 | 配合 `@JsonIgnore` 使用更精细控制 | | 前端兼容性 | 减少 JSON 体积,提高传输效率 | --- ## ✅ 注意事项 - `@JsonInclude` 只影响序列化,不影响反序列化 - 如果字段类型是基本类型(如 `int`, `boolean`),默认值是 `0` 或 `false`,使用 `NON_EMPTY` 会将其排除,可能不符合预期 - `@JsonInclude` 是 Jackson 特有的注解,Gson 或 Fastjson 有各自的实现方式 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值