我有一个JSON格式的树对象,我正试图用Gson反序列化.每个 node 都包含其子 node 作为对象类型 node 的字段. node 是一个接口,它有几个具体的类实现.在反序列化过程中,如果我事先不知道 node 属于哪种类型,我如何与Gson通信在反序列化 node 时要实现哪个具体类?每个 node 都有一个指定类型的成员字段.当对象是序列化形式时,是否有方法访问字段,并以某种方式将类型传递给Gson?
Thanks!
我有一个JSON格式的树对象,我正试图用Gson反序列化.每个 node 都包含其子 node 作为对象类型 node 的字段. node 是一个接口,它有几个具体的类实现.在反序列化过程中,如果我事先不知道 node 属于哪种类型,我如何与Gson通信在反序列化 node 时要实现哪个具体类?每个 node 都有一个指定类型的成员字段.当对象是序列化形式时,是否有方法访问字段,并以某种方式将类型传递给Gson?
Thanks!
我建议为Node
增加一个定制的JsonDeserializer:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Node.class, new NodeDeserializer())
.create();
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.