Dynamically exclude JSON fields with GSON from Object

In this tutorials we show you how to dynamically exclude JSON fields with GSON. When you have a use case that you want to exclude a field for whatever reason. You can create a custom JsonSerializer. With this serializer you can modify your exposed json object dynamically.


You must have the GSON dependency on your classpath.

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

    <name>JSON - ${project.artifactId}</name>




Object to be serialized

We will be serializing this product object.

package com.memorynotfound.json;

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;

    public long getId() {
        return id;

    public String getName() {
        return name;

    public Date getCreated() {
        return created;

    public double getAmount() {
        return amount;

Custom JsonSerializer

We can dynamically exclude a field with a custom JsonSerializer. We have a reference to our Product object which we can convert to a JsonObject. After this conversion we can check for certain conditions when we want to exclude a certain field dynamically.

package com.memorynotfound.json;

import com.google.gson.*;
import java.lang.reflect.Type;

public class ProductSerializer implements JsonSerializer<Product> {

    public JsonElement serialize(Product product, Type type, JsonSerializationContext jsc) {
        JsonObject jObj = (JsonObject)new GsonBuilder().create().toJsonTree(product);
        if (product.getAmount() > 100){
        return jObj;

Dynamically exclude JSON fields with GSON

We can add our custom ProductSerializer with the .registerTypeAdapter() method.

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);

        // normal serialization
        Gson gson = new GsonBuilder().create();
        String result = gson.toJson(product);

        // dynamic serialization on product
        gson = new GsonBuilder()
                .registerTypeAdapter(Product.class, new ProductSerializer())
        result = gson.toJson(product);


{"id":1,"name":"Playstation 4","created":"Dec 17, 2015 10:35:53 AM","amount":499.99}
{"id":1,"name":"Playstation 4","created":"Dec 17, 2015 10:35:53 AM"}


You may also like...