1

我目前正在设计基础 API 以在我的应用程序服务器中使用静态数据,我选择 Jackson 作为序列化数据的一种方式。问题是我不想在最终的 JSON 文件中进行任何嵌套,所以我最终得到了这个:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Parent {
    public long id;
    public String name;

    @JsonIdentityReference(alwaysAsId = true)
    @JsonManagedReference
    public Set<Child> children = new HashSet<>();
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Child {
    public long id;
    public String name;

    @JsonIdentityReference(alwaysAsId = true)
    @JsonBackReference
    public Parent parent;
}

public static class Registry {
    public Set<Parent> parents = new HashSet<>();
    public Set<Child> children = new HashSet<>();
}

这非常适合序列化,我得到类似:

{
    "parents" : [ {
        "id" : 1,
        "name" : "DADDY",
        "children" : [ 1, 2 ]
    } ],
    "children" : [ {
        "id" : 1,
        "name" : "JUNIOR"
    }, {
        "id" : 2,
        "name" : "JUNIOR'S SISTER"
    } ]
}

但是现在,我想反序列化它,但不幸的是抛出了一个异常:Could not resolve Object Id [2] (for [simple type, class org.photon.Main$Child])。经过一番研究,我被告知我必须实现一个自定义类型 ID 解析器,但由于缺乏资源,我无法做任何事情。我想告诉杰克逊在反序列化注册表时如何将 Parent 的实例获取给孩子,将 Child 的实例传递给父母。

你知道我该如何解决这个问题还是有其他方法可以解决?

4

0 回答 0