Home > Java > javaTutorial > body text

How to exclude a field during Gson serialization in Java?

PHPz
Release: 2023-09-23 15:09:03
forward
885 people have browsed it

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;
   }
}
Copy after login

Output

{
 "firstName": "Raja",
 "age": 28
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template