我有一个Message
类和一个HistoryMessage
类,它扩展了Message
。我如何使用Gson反序列化HistoryMessage
?
public class Message
{
@SerializedName("id")
private int id;
@SerializedName("date")
private long date;
@SerializedName("out")
private int out;
@SerializedName("user_id")
private int userId;
public Message(int id, long date, int userId, int out)
{
this.id = id;
this.date = date;
this.userId = userId;
this.out = out;
}
}
public class MessageHistory extends Message
{
@SerializedName("from_id")
private int fromId;
public MessageHistory(int id, long date, int userId, int out, int fromId)
{
super(id, date, userId, out);
this.fromId = fromId;
}
}
我有一个类 - Dialog,它是所有消息的容器
public class Dialog {
private int count;
private ArrayList<Message> dialogs = new ArrayList<Message>();
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public ArrayList<Message> getDialogs() {
return dialogs;
}
public void setDialogs(Message dialogs) {
this.dialogs.add(dialogs);
}
}
和Message
的反序列化器,但我不知道如何反序列化HistoryMessage
。
public Dialog deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Dialog dialog = new Dialog();
JsonArray jsonArray = (JsonArray)json.getAsJsonObject().get("response").getAsJsonObject().get("items");
int count = (Integer)json.getAsJsonObject().get("response").getAsJsonObject().get("count").getAsInt();
for ( int i = 0; i < jsonArray.size(); i++ ) {
JsonElement jsonElement = jsonArray.get(i);
Message message = new Message();
boolean unread = false;
if ( jsonElement.getAsJsonObject().has("unread")){
unread = true;
}
JsonObject object = (JsonObject)jsonElement.getAsJsonObject().get("message");
message = context.deserialize(object, Message.class);
message.setUnread(unread);
dialog.setDialogs(message);
}
dialog.setCount(count);
return dialog;
}
答案 0 :(得分:1)
要使用Gson,您需要指定要反序列化的类型。如果您要构建HistoryMessage
个实例,则需要将HistoryMessage.class
传递给fromJson()
来电。如果您不知道在编译时要尝试构建的类型,可以通过将类型存储在JSON中来解决它,如此答案描述:How to serialize a class with an interface?
但这绝对不是最佳做法。需要这样做表明你可能试图反序列化为太复杂的类型。考虑从业务逻辑中拆分反序列化代码,例如将您的JSON反序列化为中间类,然后从该类构造HistoryMessage
,而不是直接从JSON构建。{/ p>