如何使用Java中的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, ""); // passing null and empty fields
      String result = mapper.writeValueAsString(employee);
      System.out.println(result);
   }
}
//员工阶层
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
}