Jackson - @JsonInclude之USE_DEFAULTS

指定了JsonInclude.Include#value的USE_DEFAULTS,以便可以使用更高级别的默认值。如果在属性上使用此选项@JsonInclude,则将使用类的设置(如果存在),否则将使用全局序列化包含规则(通过设置ObjectMapper)。

例子
Java对象
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Employee {
  private String name;
  private String dept;
  private Integer salary;
  private boolean fullTime;
  @JsonInclude(JsonInclude.Include.NON_NULL)
  private List<String> phones;
  private Date dateOfBirth;
  ....

  @JsonInclude(JsonInclude.Include.USE_DEFAULTS)
  public List<String> getPhones() {
      return phones;
  }
}
Main类
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(2000));
        employee.setDateOfBirth(null);

        ObjectMapper om = new ObjectMapper();
        String jsonString = om.writeValueAsString(employee);
        System.out.println(jsonString);
    }
}
结果
{"name":"Trish","salary":2000,"fullTime":false}

如在上述输出“phones”没有被序列化,NON_NULL(在字段级别)被忽略,并使用类级别NON_EMPTY选项。如果我们移除phones的getter方法上的@JsonInclude:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Employee {
  private String name;
  private String dept;
  private Integer salary;
  private boolean fullTime;
  @JsonInclude(JsonInclude.Include.NON_NULL)
  private List<String> phones;
  private Date dateOfBirth;
  ....
  
  public List<String> getPhones() {
      return phones;
  }
}
结果集
{“ name”:“ Trish”,“ salary”:2000,“ fullTime”:false,“ phones”:[]}

这次包括了“phones”,因为它不是空的。在倒数第二个示例中,'phones’属性上的设置@JsonInclude(JsonInclude.Include.USE_DEFAULTS)可以正常工作。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值