我有一个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.

Json相关问答推荐

Elasticsearch Go客户端错误:无效的SON格式:在中间件中索引文档时出错

使用Shell深入挖掘到最低的SON元素

带有PowerShell内核的NewtonSoft json.Net的奇怪行为

将JSON输入子数组转换为字符串顺序列表输出

如何创建可由Gin序列化到json的排序键值映射?

解析JSON说函数parse_json不存在?

如何在Android中解析带有动态键和可变对象名称的改装JSON响应?

使用不同行数的数据创建嵌套Jolt

jq 中的整个单词匹配

Jolt - 在同一级别添加时组合值的问题

JBuilder中未定义的局部变量或方法json

如何使用 json.net 将数据表转换为 json 字符串?

编写 JSON 日志(log)文件的格式?

将错误消息作为 JSON 对象发送

使用绝对或相对路径在 curl 请求中发送 json 文件

JSON 使用 simplejson 序列化 Django 模型

使用 C# 调用 json

XML vs YAML vs JSON

添加json文件注释

使用 JSON.NET 序列化/反序列化对象字典