我有两个班级:Player
和Match
。
Player
有两个字段playerId
和name
,而Match
包含两个Player
对象,也包含matchId
。
当我序列化Player
时,我确实希望ID和名称出现在JSON中,但是当我序列化Match
时,我得到matchId
和Player
的非即使我只想获得Player
的{{1}},也可以使用瞬态字段及其各自的值。
我该如何使用Gson?
答案 0 :(得分:0)
您可以使用Gson的@Expose批注仅公开该字段。您将必须通过调用GsonBuilders excludeFieldsWithoutExposeAnnotation()函数来构建Gson对象。
class Player {
@Expose
private final int id;
//constructor, etc
}
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();