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



Serialization is the process that converts an object into a format that can be stored or transmitted easily.

Excluding a Field in Gson During Serialization

We might have some scenarios where we are asked or required to exclude a certain field from the object while serializing it. For example, we have a Student object with fields like name, age, and address. We want to serialize the object but exclude the address field for building basic information about the student in this case, we use

In this article, we will learn how to exclude a field in Gson during serialization in Java. We will use a method called excludeFieldsWithoutExposeAnnotation() to exclude the field. Now, let's see how we can use the Gson library. If you are using Maven, add this to your pom.xml file:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

If you do not use Maven, you can download the jar file from here.

Steps

Following are the steps to exclude a field in Gson during serialization in Java:

  • Define your data class (e.g., Person) with fields and getters.
  • Annotate the field you want to exclude with @Expose(serialize = false).
  • In your main code, create an instance of the Person class.
  • Instantiate a Gson object with GsonBuilder.
  • Call gson.toJson(yourObject) to get the JSON string.

Example

Following is an example to exclude a field in Gson during serialization in Java. In here, we will create a class Person with fields for name and age. We will exclude the age field during serialization using Gson.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class GsonExample {
   public static void main(String[] args) {
      // Create an instance of the Person class
      Person person = new Person("Ansh", 23);

      // Create a Gson object with Expose handling
      Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

      // Convert the Person object to JSON
      String json = gson.toJson(person);

      System.out.println(json);
   }
}

class Person {
   @SerializedName("name")
   @Expose
   private String name;

   @Expose(serialize = false)
   private int age;

   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }

   public String getName() {
      return name;
   }

   public int getAge() {
      return age;
   }
}

Output

Following is the output of the above code:

{"name":"Ansh"}
Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2025-05-13T17:38:16+05:30

666 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements