首页 >Java >java教程 >如何在Java中使用ExclusionStrategy接口对JSON进行序列化和反序列化?

如何在Java中使用ExclusionStrategy接口对JSON进行序列化和反序列化?

PHPz
PHPz转载
2023-08-20 21:53:241224浏览

如何在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删除