如何使用Gson反序列化继承公共基类的类型



我有以下层次结构:

响应

public class Response implements Serializable {
@SerializedName("message")
@Expose
private List<Message> messages;
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
}

消息

public class Message implements Serializable {
@SerializedName("type")
@Expose
@MessageType
private int type;
@SerializedName("position")
@Expose
@MessagePosition
private String position;
public int getType() {
return type;
}
public String getPosition() {
return position;
}
public void setType(@MessageType int type) {
this.type = type;
}
public void setPosition(@MessagePosition String position) {
this.position = position;
}
}

文本->消息

public class TextMessage extends Message {
@SerializedName("text")
@Expose
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}

}

图像->消息

public class ImageMessage extends Message {
@SerializedName("attachment")
@Expose
private Attachment attachment;
public Attachment getAttachment() {
return attachment;
}
public void setAttachment(Attachment attachment) {
this.attachment = attachment;
}
}

尝试使用GSon以这种方式反序列化Message(自然)会导致textattachment字段为空我希望有一个最适合的反序列化,它将根据响应在运行时选择与大多数字段匹配的消息类型(即文本或图像)

到目前为止,我唯一的想法是:

1-使用@JsonAdapter->不起作用

2-创建另一个层次结构,在编译时指向类,如:

---- Response
|
- TextResponse -> List<TextMessage>
|
- ImageResponse -> List<ImageMessage>

第二个选项并不是我真正想要的,它使我以一种可能变得过于复杂的方式来乘以类的数量,从而无法应用以后的维护。

有人知道处理这个问题的方法吗?有什么可以应用的框架或概念吗?

提前感谢

也许您可以使用Gson extraRunTimeTypeAdapterFactory。检查此示例:

RuntimeTypeAdapterFactory<Message> factory = RuntimeTypeAdapterFactory
.of(Message.class, "type") // actually type is the default field to determine
// the sub class so not needed to set here
// but set just to point that it is used
// assuming value 1 in field "int type" identifies TextMessage
.registerSubtype(TextMessage.class, "1")
// and assuming int 2 identifies ImageMessage
.registerSubtype(ImageMessage.class, "2");

然后使用GsonBuilder.registerTypeAdapterfactory(factory)来使用此。

这是Gson核心库中找不到的。你需要在这里取。您还可以从全局回购中找到一些Maven/Gradle dep,这是有人做过的,但最简单的方法可能只是复制这个文件。

如果你需要修改它的行为,它会启用以后的黑客攻击。

我用具有所有消息类型字段的GodClass实现了这一点。

但是在您的应用程序中,您不会将这个POJO类用作DTO(数据传输对象)。

Json是一个协议,不支持Inheritance

在同一个场景中,我为DTO实现了这种继承和层次结构。

PS:我的答案中的DTO是我们通过的模型,例如AdapterActivity等等

最新更新