Home >Java >javaTutorial >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 .
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; } }
{ "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!