首頁 > Java > java教程 > 如何在Java中忽略JSON物件的多個屬性?

如何在Java中忽略JSON物件的多個屬性?

王林
發布: 2023-09-18 22:29:02
轉載
708 人瀏覽過

如何在Java中忽略JSON物件的多個屬性?

@JsonIgnoreProperties#Jackson 註解可用於指定要忽略的類別的屬性清單欄位@JsonIgnoreProperties##annotation 

可以放置在類別宣告之前,而不是放置在單一屬性或欄位之前忽略。

語法

@Target(value={ANNOTATION_TYPE,TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnoreProperties
登入後複製

範例

import java.io.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
public class JsonIgnorePropertiesTest {
   public static void main(String[] args) throws IOException {
      Customer customer = new Customer("120", "Ravi", "Hyderabad");
      System.out.println(customer);
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writeValueAsString(customer);
      System.out.println("JSON: " + jsonString);
      System.out.println("---------");
      jsonString = "{\"id\":\"130\",\"name\":\"Rahul\", \"address\":\"Mumbai\"}";
      System.out.println("JSON: " + jsonString);
      customer = mapper.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer class
@JsonIgnoreProperties({"id", "address"}) <strong>
</strong>class Customer {
   private String id;
   private String name;
   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;
   }
<strong>   </strong>@Override
   public String toString() {
      return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}
登入後複製

輸出

Customer [id=120, name=Ravi, address=Hyderabad]
JSON: {"name":"Ravi"}
---------
JSON: {"id":"130","name":"Rahul", "address":"Mumbai"}
Customer [id=null, name=Rahul, address=null]
登入後複製
###

以上是如何在Java中忽略JSON物件的多個屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板