Conditionally serialise fields in Gson

Fares :

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?

Thanks in advance and stay safe. Fares

Jason :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=385224&siteId=1