首頁  >  文章  >  Java  >  如何使用Java中的Jackson庫忽略空和空字段?

如何使用Java中的Jackson庫忽略空和空字段?

WBOY
WBOY轉載
2023-08-30 13:17:05784瀏覽

如何使用Java中的Jackson庫忽略空和空字段?

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);
   }
}
// Employee class
class Employee {
   private int id;
   @JsonInclude(Include.NON_NULL)
   private String firstName;
   @JsonInclude(Include.NON_EMPTY)<strong>
</strong>   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;
   }
}

輸出

<strong>{
 "id" : 115
}</strong>

以上是如何使用Java中的Jackson庫忽略空和空字段?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除