GSON - Excluding fields from JSON with @Expose Annotation

In this quick article, we will discuss how to mark certain fields of our Java objects to be excluded for consideration for serialization and deserialization to JSON.

Java Modifier Exclusion

By default, if you mark a field as transient, it will be excluded. As well, if a field is marked as static then by default it will be excluded. If you want to include some transient fields then you can do the following:
import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
    .excludeFieldsWithModifiers(Modifier.STATIC)
    .create();
NOTE: you can give any number of the Modifier constants to the excludeFieldsWithModifiers method. For example:
Gson gson = new GsonBuilder()
    .excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE)
    .create();

Gson's @Expose

To use this @Expose GSON annotation, you must create Gson by using new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). The Gson instance created will exclude all fields in a class that is not marked with a @Expose annotation.

Gson Maven Dependency

To use Gson with Maven2/3, you can use the Gson version available in Maven Central by adding the following dependency:
<dependencies>
    <!--  Gson: Java to Json conversion -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
      <scope>compile</scope>
    </dependency>
</dependencies>

User Class - Object to be Serialized/Deserialized

The fields that are marked with the @Expose annotation will be included in the JSON representation. So the fields that are not annotated e.g.: “id, firstName, lastName” will not be serialized into the JSON object.
package net.javaguides.gson;

import com.google.gson.annotations.Expose;

/**
 * 
 * @author Ramesh Fadatare
 *
 */

public class User {

    private int id;
    private String firstName;
    private String lastName;

    @Expose
    private int age;

    @Expose
    private String gender;

    @Expose
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int i) {
        this.id = i;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", gender=" +
            gender + "]";
    }
}

Excluding field from JSON using @Expose GSON

When creating your JSON object you must create Gson by using new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). Otherwise, the JSON object will not listen to the @Expose annotation.
package net.javaguides.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class GSONExcludingFieldsExample {
    public static void main(String[] args) {

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        User user = new User();
        user.setFirstName("Ramesh");
        user.setLastName("Fadatare");
        user.setGender("Male");
        user.setAge(28);
        user.setId(100);
        user.setPassword("secret");

        // Serialization without excludeFieldsWithoutExposeAnnotation() method
        String userJson = gson.toJson(user);
        System.out.println(userJson);

        // Serialization with excludeFieldsWithoutExposeAnnotation() method
        gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
        String result = gson.toJson(user);
        System.out.println("-------- Serialization using @Expose annotation -----");
        System.out.println(result);
    }
}
Output:
{
  "id": 100,
  "firstName": "Ramesh",
  "lastName": "Fadatare",
  "age": 28,
  "gender": "Male",
  "password": "secret"
}
-------- Serialization using @Expose annotation -----
{
  "age": 28,
  "gender": "Male",
  "password": "secret"
}
Note that the fields - id, firstName, and lastName are not annotated with @Expose so they are excluded from JSON serialization.

Reference

Comments