Home >Java >javaTutorial >How to exclude a field during Gson serialization in Java?

How to exclude a field during Gson serialization in Java?

PHPz
PHPzforward
2023-09-23 15:09:03931browse

How to exclude a field during Gson serialization in Java?

The Gson library provides an easy way to exclude fields from serialization using the transient modifier. If we set fields in a Java class to be transient, Gson can ignore their 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.<strong>toJson</strong>(p);
      System.out.println(jsonStr);
   }
}
//Person class<strong>
</strong>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
}

The above is the detailed content of How to exclude a field during Gson serialization in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete