如何使用 Java 中的 Jackson 庫忽略空和 null 欄位?\n


Jackson 是一個用於 Java 的庫,它具有非常強大的資料繫結功能,並提供了一個框架,可將 自定義 Java 物件序列化為 JSON,並將 JSON 反序列化回 Java 物件。Jackson 庫提供了 @JsonInclude 註釋,該註釋根據序列化期間的屬性值控制整個類的序列化及其各個欄位的序列化。

@JsonInclude 註釋包含以下兩個值

  • Include.NON_NULL:表示僅包含非 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);
   }
}
// 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
}

更新於: 06-Jul-2020

2K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.