Java Gson Excluding Fields with @Expose Example

Gson @Expose annotation indicates that a member should be exposed to JSON serialization or deserialization. The @Expose annotation can take two boolean parameters: serialize and deserialize. The @Expose annotation must be explicitly enabled with excludeFieldsWithoutExposeAnnotation() method.
Gson is a Java serialization/deserialization library to convert Java Objects into JSON and back. Gson was created by Google for internal use and later open-sourced.

Java Gson Maven dependency

This is a Maven dependency for Gson.
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

Java Gson Excluding Fields with @Expose Example

In the example, we exclude one field from serialization.
package net.javaguides.gson;

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

enum MaritalStatus {

    SINGLE,
    MARRIED,
    DIVORCED,
    UNKNOWN
}

class Person {

    @Expose
    private String firstName;

    @Expose
    private String lastName;

    private MaritalStatus maritalStatus;

    public Person(String firstName, String lastName,
        MaritalStatus maritalStatus) {

        this.firstName = firstName;
        this.lastName = lastName;
        this.maritalStatus = maritalStatus;
    }

    public Person() {}
}

public class GsonExcludeFileds {

    public static void main(String[] args) {

        Gson gson = new GsonBuilder()
            .excludeFieldsWithoutExposeAnnotation()
            .setPrettyPrinting()
            .create();

        Person p = new Person("Jack", "Sparrow", MaritalStatus.UNKNOWN);

        gson.toJson(p, System.out);
    }
}
Output:
{
  "firstName": "Jack",
  "lastName": "Sparrow"
}

The marital status field will not be serialized, because it is not decorated with the @Expose annotation.
@Expose
private String firstName;

@Expose
private String lastName;

private MaritalStatus maritalStatus;

Reference


Comments