Excluding field from JSON with @Expose GSON

GSON provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. 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 are not marked with @Expose annotation.

Maven dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">




Object to be Serialised/Deserialised

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.: “created” will not be serialised into the JSON object.

package com.memorynotfound.json;

import com.google.gson.annotations.Expose;

import java.util.Date;

public class Product {

    private long id;
    private String name;
    private Date created;
    private double amount;

    public Product(long id, String name, Date created, double amount) {
        this.id = id;
        this.name = name;
        this.created = created;
        this.amount = amount;

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 com.memorynotfound.json;

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

import java.util.Date;

public class ExcludeExposeGson {

    public static void main(String... args){
        Product product = new Product(1, "Playstation 4", new Date(), 499.99);
        Gson gson = new GsonBuilder().create();
        String result = gson.toJson(product);

        gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        result = gson.toJson(product);


{"id":1,"name":"Playstation 4","created":"Dec 26, 2014 4:23:59 PM","amount":499.99}
{"id":1,"name":"Playstation 4","amount":499.99}


You may also like...