GSON Excluding fields with modifiers from JSON

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. Here is another way you can exclude fields from GSON using modifiers.

Maven dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""




Object to be Serialised/Deserialised

Note: that the id field has a protected modifier.

package com.memorynotfound.json;

import java.util.Date;

public class Product {

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

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

GSON Excluding fields with modifiers from JSON

You must inform GSON to exclude certain fields. You can exclude fields by modifier using new GsonBuilder().excludeFieldsWithModifiers() and insert the modifiers that you want to exclude.

You can pass in a list of Modifiers like: Modifier.PROTECTED, Modifier.VOLATILE.
package com.memorynotfound.json;


import java.lang.reflect.Modifier;
import java.util.Date;

public class ExcludeModifiersGson {

    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().excludeFieldsWithModifiers(Modifier.PROTECTED).create();
        result = gson.toJson(product);


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


You may also like...