Sometimes you don't want to include certain fields for Serialization/Deserialization. Gson provides a couple of ways to do this. In this tutorial i'm going to talk about the @Expose annotation. You must use @Expose together with new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); in order for it to work.

If you use @Expose on a field you're telling Gson to include that property into your JSON String. All the fields that arn't annotated with the @Expose will be excluded




Maven configuration



Java Bean


With Gson's @Expose annotation you can mark your fields of your objects to be excluded. To use this annoation you must create Gson by using new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). The fields that are not marked as @Expose will not be Serialized/Desirialized.


package org.camelcode;

import com.google.gson.annotations.Expose;

public class Book {

    @Expose
    private String author;
    @Expose
    private String title;
    private Integer year;
    private Double price;

    public Book() {
        this("camelcode.org", "Exclude properties with Gson", 1989, 49.55);
    }

    public Book(String author, String title, Integer year, Double price) {
        this.author = author;
        this.title = title;
        this.year = year;
        this.price = price;
    }
}


Helper class


By using the new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(), you tell gson to exclude all the fields for Serialization/Desirialization that are not marked with @Expose.


package org.camelcode;

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

public class WriteGson {

    public static void main(String[] args) {

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

        String json = gson.toJson(new Book());
        System.out.println(json);

        Gson gsonNonExcluded = new Gson();
        String jsonNonExcluded = gsonNonExcluded.toJson(new Book());
        System.out.println(jsonNonExcluded);
    }
}


Output

{"author":"camelcode.org","title":"Exclude properties with Gson"}
{"author":"camelcode.org","title":"Exclude properties with Gson","year":1989,"price":49.55}


Download


Download source code - Exclude-Fields-From-JSON-with-GSON-@Expose.zip  2 KB