有条件地序列化Gson中的字段

时间:2020-03-31 20:26:50

标签: java json gson

我有两个班级:PlayerMatch

Player有两个字段playerIdname,而Match包含两个Player对象,也包含matchId

当我序列化Player时,我确实希望ID和名称出现在JSON中,但是当我序列化Match时,我得到matchIdPlayer的非即使我只想获得Player的{​​{1}},也可以使用瞬态字段及其各自的值。

我该如何使用Gson?

1 个答案:

答案 0 :(得分:0)

您可以使用Gson的@Expose批注仅公开该字段。您将必须通过调用GsonBuilders excludeFieldsWithoutExposeAnnotation()函数来构建Gson对象。

class Player {

    @Expose
    private final int id;

    //constructor, etc

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