首頁  >  文章  >  Java  >  如何在Java中使用ExclusionStrategy介面對JSON進行序列化與反序列化?

如何在Java中使用ExclusionStrategy介面對JSON進行序列化與反序列化?

PHPz
PHPz轉載
2023-08-20 21:53:241210瀏覽

如何在Java中使用ExclusionStrategy介面對JSON進行序列化與反序列化?

ExclusionStrategy介面可以在序列化和反序列化過程中用來排除任何欄位。我們可以提供ExclusionStrategy介面的自訂實現,並使用setExclusionStrategies()方法將其註冊到GsonBuilder中。它配置Gson在序列化和反序列化過程中應用一組排除策略。

語法

public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies)

Example

import com.google.gson.*;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
public class ExclusionStrategyTest {
   public static void main(String args[]) throws Exception {
      <strong>Gson </strong>gson = new GsonBuilder().setExclusionStrategies(new CustomExclusionStrategy()).create();
         Person person = new Person();
         person.setFirstName("Adithya");
         person.setLastName("Sai");
         person.setAddress("Hyderabad");
         String jsonString = gson.toJson(person);
         System.out.println("Serialize a JSON: \n "+jsonString);
         String inputJson = "{\"firstName\":\"Raja\", \"lastName\":\"Ramesh\", \"address\":\"Hyderabad\"}";
         person = gson.fromJson(inputJson, Person.class);
         System.out.println("Deserialize a JSON:\n"+ person);
      }
   }
   // CustomExclusionStrategy class
class CustomExclusionStrategy implements ExclusionStrategy {
   public boolean shouldSkipField(FieldAttributes f) {
      if(f.getName().equals("firstName")) {
         return true;
      }
      return false;
   }
   public boolean shouldSkipClass(Class aClass) {
      return false;
   }
}
// Person class
class Person {
   private String firstName, lastName, address;
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String geLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public String toString() {
      return "Person [" + firstName + " " + lastName + " " + address + "]";
   }
}

Output

Serialize a JSON:
{"lastName":"Sai","address":"Hyderabad"}
Deserialize a JSON:
Person [null Ramesh Hyderabad]

以上是如何在Java中使用ExclusionStrategy介面對JSON進行序列化與反序列化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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