How to serialize and deserialize a JSON using the ExclusionStrategy interface in Java?

JavaJSONObject Oriented ProgrammingProgramming

The ExclusionStrategy interface can be used to exclude any field during serialization and deserialization. We can provide a custom implementation of the ExclusionStrategy interface and need to register it with GsonBuilder using the setExclusionStrategies() method. It configures Gson to apply a set of exclusion strategies during serialization and deserialization.


public GsonBuilder setExclusionStrategies(ExclusionStrategy... strategies)


public class ExclusionStrategyTest {
   public static void main(String args[]) throws Exception {
      Gson gson = new GsonBuilder().setExclusionStrategies(new CustomExclusionStrategy()).create();
         Person person = new Person();
         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:
Deserialize a JSON:
Person [null Ramesh Hyderabad]
Updated on 08-Jul-2020 06:48:57