【发布时间】:2018-12-23 10:15:23
【问题描述】:
我正在尝试使用 Gson 将一个非常基本的对象序列化为 JSON。
这是课程
@org.greenrobot.greendao.annotation.Entity
public class Giveaway {
@Id(autoincrement = true)
@Expose(serialize = false,deserialize = false)
private Long id;
@NotNull
private String owner;
private Date raffleDate;
private String thumbnailUrl;
@ToMany(referencedJoinProperty = "giveawayId")
private List<Influencer> mustFollowList;
@NotNull
@Convert(converter = GiveawayCommentTypeConverter.class, columnType = Integer.class)
private GiveawayCommentType tipo;
private String specifWordValue;
private Integer amountFriendsToIndicate;
@NotNull
@Unique
private String mediaId;
//to reflect the relationships
@ToMany(referencedJoinProperty = "raffle")
@Expose(deserialize = false, serialize = false)
private List<UserOnGiveaway> attendantsTickets;
}
如您所见,我有 2 个字段我不想被序列化,所以我用 expose = false 注释它们,但即使使用这个 Gson 试图序列化它们并由于 OutOfMemory 而崩溃。 (UserOnGiveaway 对 Giveaway 有一个循环引用,这解释了它崩溃的原因。)
Gson 代码是:
Gson parser = new GsonBuilder().setPrettyPrinting().excludeFieldsWithModifiers(Modifier.FINAL, Modifier.STATIC, Modifier.TRANSIENT).create();
StringBuilder sb = new StringBuilder(200);
try {
for (Giveaway g : this.dao.getGiveawayDao().loadAll())
sb.append(parser.toJson(g) + "\n");
} catch (Exception e) {
e.printStackTrace();
}
我不想使用.excludeFieldsWithoutExposeAnnotation(),因为它迫使我编写不必要的内容并注释所有内容以排除 1 个字段...
我做错了什么?
【问题讨论】: