如何使用 Java 中的 ExclusionStrategy 接口来序列化和反序列化 JSON?
ExclusionStrategy 接口可用于在序列化和反序列化期间排除任何字段。我们可以提供ExclusionStrategy 接口的自定义实现,并且需要使用setExclusionStrategies() 方法将其注册到GsonBuilder 中。它会将 Gson 配置为在序列化和反序列化期间应用一组排除策略。
语法
public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies)
示例
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 { Gson 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 + "]"; } }
输出
Serialize a JSON: {"lastName":"Sai","address":"Hyderabad"} Deserialize a JSON: Person [null Ramesh Hyderabad]
广告