反序列化 Gson 中的抽象类 [英] Deserializing an abstract class in Gson

查看:34
本文介绍了反序列化 Gson 中的抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JSON 格式的树对象,我正在尝试使用 Gson 反序列化.每个节点都包含其子节点作为对象类型节点的字段.Node 是一个接口,它有几个具体的类实现.在反序列化过程中,如果我不知道节点属于哪种类型的先验,我如何与 Gson 通信在反序列化节点时要实现的具体类?每个节点都有一个成员字段指定类型.当对象处于序列化形式时,有没有办法访问该字段,并以某种方式将类型传达给 Gson?

I have a tree object in JSON format I'm trying to deserialize with Gson. Each node contains its child nodes as fields of object type Node. Node is an interface, which has several concrete class implementations. During the deserialization process, how can I communicate to Gson which concrete class to implement when deserializing the node, if I do not know a priori which type the node belongs to? Each Node has a member field specifying the type. Is there a way to access the field when the object is in serialized form, and somehow communicate the type to Gson?

谢谢!

推荐答案

我建议添加一个自定义的 JsonDeserializer 用于Nodes:

I'd suggest adding a custom JsonDeserializer for Nodes:

Gson gson = new GsonBuilder()
    .registerTypeAdapter(Node.class, new NodeDeserializer())
    .create();

您将能够在反序列化器的方法中访问表示节点的 JsonElement,将其转换为 JsonObject,并检索指定类型的字段.然后,您可以基于此创建正确类型的 Node 实例.

You will be able to access the JsonElement representing the node in the deserializer's method, convert that to a JsonObject, and retrieve the field that specifies the type. You can then create an instance of the correct type of Node based on that.

这篇关于反序列化 Gson 中的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆