【发布时间】:2017-05-05 20:33:09
【问题描述】:
我有一个非常具体的使用 GSON 进行自定义序列化的案例:
假设我有以下课程:
public class Student extends BaseModel{
private int id;
private String name;
private Student goodFriend;
private Student bestFriend;
}
BaseModel 只是我所有模型类的基类。
当我简单地做的时候
gson.toJson(student /* Some Student instance */);
我会得到例如:
{
id: 1,
name: "Jack",
goodFriend: {id: 2, name: "Matt"},
bestFriend: {id: 3, name "Tom"}
}
没关系,但我需要的是这个:
{
id: 1,
name: "Jack",
goodFriend: 2, // only an ID for this field
bestFriend: {id: 3, name "Tom"} // whole object for this field
// both fields are of the same Type, so I can't use TypeAdapterFactory for this
}
我需要一些方法来标记具有序列化类型(id 或对象)的字段,然后根据需要使用该标记进行序列化。我如何在general 中做到这一点,不仅适用于 Student 类,而且适用于 BaseModel 的所有子类?
我唯一的想法是使用自定义注释: 仅使用一个注释描述我想序列化为 ID 的字段,以及我想使用另一个注释将其序列化为对象的字段, 但是我找不到在 TypeAdapter 的 write 方法中检索注解的方法。
任何想法如何处理这个?
【问题讨论】:
标签: java android reflection annotations gson