Conditionally serialise fields in Gson

Tags: , ,



I have two classes : Player and Match.

Player has two fields, playerId and name while Match contains two Player objects and matchId too.

When I serialise Player I do want the id and the name to appear in the JSON, however when I serialise Match I get matchId and Player‘s non transient fields and their respective values even though I’d like to only get Player‘s ids.

How do I do this with Gson?

Answer

You can use Gson’s @Expose annotation to only expose that field. You will have to build your Gson object by calling GsonBuilders excludeFieldsWithoutExposeAnnotation() function.

class Player {

    @Expose
    private final int id;

    //constructor, etc

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


Source: stackoverflow