Exclude Fields from Serialization in Gson – @Expose Annotation

When working with JSON serialization and deserialization using Gson, we often encounter scenarios where certain fields in a class should not be included in the JSON output or input. The @Expose annotation in Gson provides an elegant way to handle such cases. In this blog post, we’ll explore how the @Expose annotation works, its significance, and how to use it effectively in your Java projects.


Understanding @Expose in Gson

Gson is a powerful library for converting Java objects to JSON and vice versa. By default, Gson serializes all fields in a class unless explicitly configured otherwise. However, there may be cases where some fields are sensitive, irrelevant, or unnecessary for the serialization/deserialization process.

The @Expose annotation allows developers to mark specific fields for inclusion or exclusion during serialization and deserialization. When Gson's GsonBuilder is configured with .excludeFieldsWithoutExposeAnnotation(), only fields annotated with @Expose will be processed.


How Does @Expose Work?

The @Expose annotation provides two optional attributes:

  • serialize: Determines whether the field should be included during serialization.
  • deserialize: Determines whether the field should be considered during deserialization.

Both attributes default to true. If you don’t specify them, the field will be included in both serialization and deserialization processes by default.


Using @Expose – A Step-by-Step Guide

1. Add Gson Dependency

Ensure you have Gson added to your project. For a Maven project, include the following dependency in your pom.xml:

<dependency>

    <groupId>com.google.code.gson</groupId>

    <artifactId>gson</artifactId>

    <version>2.10.1</version>

</dependency>

2. Create a Java Class with Fields

Here’s an example class with various fields:

import com.google.gson.annotations.Expose;


public class User {

    @Expose

    private String name;


    @Expose(serialize = true, deserialize = false)

    private String password;


    @Expose(serialize = false, deserialize = true)

    private String role;


    private int age; // Not annotated, will be excluded if excludeFieldsWithoutExposeAnnotation is used


    // Getters and setters

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }


    public String getPassword() { return password; }

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


    public String getRole() { return role; }

    public void setRole(String role) { this.role = role; }


    public int getAge() { return age; }

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

}

3. Configure Gson with @Expose

Use the GsonBuilder to enable @Expose processing:

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;


public class Main {

    public static void main(String[] args) {

        User user = new User();

        user.setName("John Doe");

        user.setPassword("securePassword123");

        user.setRole("Admin");

        user.setAge(30);


        // Gson with @Expose processing

        Gson gson = new GsonBuilder()

                .excludeFieldsWithoutExposeAnnotation()

                .create();


        // Serialize to JSON

        String json = gson.toJson(user);

        System.out.println("Serialized JSON: " + json);


        // Deserialize from JSON

        String jsonInput = "{\"name\":\"Jane Doe\",\"password\":\"newPassword\",\"role\":\"User\",\"age\":25}";

        User deserializedUser = gson.fromJson(jsonInput, User.class);

        System.out.println("Deserialized User: ");

        System.out.println("Name: " + deserializedUser.getName());

        System.out.println("Password: " + deserializedUser.getPassword());

        System.out.println("Role: " + deserializedUser.getRole());

        System.out.println("Age: " + deserializedUser.getAge());

    }

}

Expected Output

Serialized JSON

With @Expose processing enabled, the age field is excluded because it lacks the @Expose annotation:

{"name":"John Doe","password":"securePassword123"}

Deserialized Object

Fields configured with deserialize = false (like password) will not be populated during deserialization:

Deserialized User: 

Name: Jane Doe

Password: null

Role: User

Age: 0

Why Use @Expose?

  1. Fine-Grained Control: Choose exactly which fields to include or exclude during serialization and deserialization.
  2. Security: Prevent sensitive fields from being serialized inadvertently.
  3. Custom Behavior: Handle scenarios where some fields are only relevant for specific operations like sending data over an API.

Key Points to Remember

  1. Defaults: Without @Expose, Gson includes all fields by default.
  2. Annotation Dependency: The @Expose annotation only works when excludeFieldsWithoutExposeAnnotation() is enabled in GsonBuilder.
  3. Custom Attributes: Use serialize and deserialize to control field behavior more precisely.

Followers