java - JSON多态反序列化java
问题描述
我有一个 JSON 格式的文件系统结构,如下所示:
{
"name": "rootf",
"type": "system",
"path": "Parsing/rootf",
"children": [{
"name": "f1",
"type": "folder",
"path": "Parsing/rootf/f1",
"children": [{
"name": "subf1",
"type": "folder",
"path": "Parsing/rootf/f1/subf1",
"children": [{
"name": "text1.txt",
"type": "file",
"path": "Parsing/rootf/folder1/subf1/text1.txt",
"children": ["a", "b", "c"]
}]
}, {
"name": "subf2",
"type": "folder",
"path": "Parsing/rootf/f1/subf2",
"children": []
}, {
"name": "text2.txt",
"type": "file",
"path": "TParsing/rootf/f1/text2.txt",
"children": ["d", "e", "f"]
}]
}, {
"name": "text1.txt",
"type": "file",
"path": "Parsing/rootd/text1.txt",
"children": ["aa", "bb"]
}],
"_id": "5ce47292d866fc2f40037a56"
}
可以看出,类型system
(表示根文件夹)和类型folder
(表示根文件夹的子文件夹)的子级可以包含其他文件夹和/或文件。文件类型的子项包含文件的内容。我有一个抽象类Component
:
public abstract class Component implements IComponent{
private String name;
private String type;
private String path;
public abstract <T extends IComponent> ISystem<T> getSystem();
}
和另一个抽象类SystemAdapter
:
public abstract class SystemAdapter<T extends IComponent>
implements ISystem<T> {
private LinkedHashSet<ComponentType> components;
protected abstract Set<ComponentType> components();
public Set<ComponentType> getComponents() {
return components;
}
我有 3 个具体类扩展了两个抽象类:
public class System extends SystemAdapter{
public transient Set<ComponentWrapper> components;
private List<????> children;
private String name;
private String id;
private String type;
private String path;
public class Folder extends Component{
public List<????> children = new ArrayList<>();
private String name;
private String type;
private String path;
public class File extends Component{
public List<String> children = new ArrayList<>();
private String name;
private String type;
private String path;
我一直在努力将我拥有的 JSON 映射到这三个类。既children
可以是类型Folder
,File
又可以如何映射?我的目标是将system
类型(即根文件夹)映射到System.java
,folder
键入到Folder.java
并将file
JSON 键入到File.java
.
第二部分是能够获取components
特定系统的文件并为特定的system
获取所有的集合components
(即,为特定的根文件夹获取其所有文件和子文件夹)。
我看到了一些与 JSON 的多态反序列化相关的问题,但我不确定这是否适合这里。任何指导都会非常有帮助。
解决方案
这取决于您在 Java 中使用的库,但如果您使用的是Jackson
,您可以使用其中的值对抽象类Component
进行反序列化。type
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Folder.class, name = "folder")
@JsonSubTypes.Type(value = File.class, name = "file")
})
public abstract class Component implements IComponent{
//...
}
这基本上会告诉杰克逊在现场Folder
读取时启动 a ,对于现场也是如此。folder
type
file
推荐阅读
- amazon-web-services - AWSElasticBeanstalkFullAccess(提供完全访问权限...)等效?
- javascript - 如何确定使用的 avro 版本?
- c++ - Qt:Linux下Windows格式数据的安全解析
- powershell - Powershell脚本将一列拆分为两列
- reactjs - 在 React 中为我当前的资金添加一些钱
- hive - 是否可以在 hive SQL 中 concat_ws 多列?
- javascript - angularjs ui-router嵌套状态新控制器不起作用
- python - YAML 中使用的参数与 Ultralytics 的 yolov5 实现中的类参数之间有什么关系?
- java - 在 STS 中单独运行 jhipster 测试用例
- open-telemetry - 将 opentelemetry 收集器自己的日志写入文件