首頁 >Java >java教程 >如何在Java中使用Jackson庫忽略JSON物件的欄位?

如何在Java中使用Jackson庫忽略JSON物件的欄位?

PHPz
PHPz轉載
2023-09-12 09:41:071481瀏覽

如何在Java中使用Jackson庫忽略JSON物件的欄位?

Jackson @JsonIgnore 註解可用於忽略某個屬性欄位一個Java 物件。將 JSON 讀入 Java 物件以及將 Java 物件寫入 JSON 時,都可以忽略該屬性。我們可以使用ObjectMapper類別的readValue()writeValueAsString()方法將JSON讀取為Java物件並將Java物件寫入JSON。

語法

@Target(value={ANNOTATION_TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnore

範例

import java.io.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
public class JsonIgnoreTest {
   public static void main(String[] args) throws IOException {
      Customer customer = new Customer("110", "Surya Kiran", "Chennai");
      System.out.println(customer);
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writeValueAsString(customer);
      System.out.println("JSON: " + jsonString);
      System.out.println("---------");
      jsonString = "{\"id\":\"120\",\"name\":\"Devaraj\", \"address\":\"Banglore\"}";
      System.out.println("JSON: " + jsonString);
      customer = mapper.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer class<strong>
</strong>class Customer {
   private String id;
   private String name;
<strong>  </strong> @JsonIgnore<strong>
</strong>   private String address;
   public Customer() {
   }
   public Customer(String id, String name, String address) {
      this.id = id;
      this.name = name;
      this.address = address;
   }
   public String getId() {
      return id;
   }
   public String getName() {
      return name;
   }
   public String getAddress() {
      return address;
   }
   @Override
   public String toString() {
      return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}

輸出

Customer [id=110, name=Surya Kiran, address=Chennai]
JSON: {"id":"110","name":"Surya Kiran"}
---------
JSON: {"id":"120","name":"Devaraj", "address":"Banglore"}
Customer [id=120, name=Devaraj, address=null]

以上是如何在Java中使用Jackson庫忽略JSON物件的欄位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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