首页 > 解决方案 > 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可以是类型FolderFile又可以如何映射?我的目标是将system类型(即根文件夹)映射到System.javafolder键入到Folder.java并将fileJSON 键入到File.java.

第二部分是能够获取components特定系统的文件并为特定的system获取所有的集合components(即,为特定的根文件夹获取其所有文件和子文件夹)。

我看到了一些与 JSON 的多态反序列化相关的问题,但我不确定这是否适合这里。任何指导都会非常有帮助。

标签: javajson

解决方案


这取决于您在 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 ,对于现场也是如此。foldertypefile


推荐阅读