How to exclude a field in Gson during serialization in Java?

JavaJSONObject Oriented ProgrammingProgramming

The Gson library provided a simple approach to exclude fields from serialization using a transient modifier. If we make a field in a Java class as transient then Gson can ignore for both serialization and deserialization.

Example

import com.google.gson.*;
public class GsonTransientFieldTest {
   public static void main(String[] args) {
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      Person p = new Person("Raja", "Ramesh", 28, 35000.00);
      String jsonStr = gson.toJson(p);
      System.out.println(jsonStr);
   }
}
//Person class
class Person {
   private String firstName;
   private transient String lastName;
   private int age;
   private transient double salary;
   public Person(String firstName, String lastName, int age, double salary) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.salary = salary;
   }
}

Output

{
 "firstName": "Raja",
 "age": 28
}
raja
Published on 03-Oct-2019 10:45:19
Advertisements