杰克逊上下文JsonBackReference?

时间:2016-03-04 12:06:56

标签: java json rest jackson

假设我有一个像这样的父类:

public class Parent {
    @JsonManagedReference
    private List<Child> children;

    private String name;

    ... other Bean stuff ...
}

这样的儿童班:

public class Child {
    @JsonBackReference
    private Parent parent;

    private String name;
    ... other Bean stuff ...
}

现在假设我将代码称为:

    // Set up the family with bidirectional links
    Parent zeus = new Parent();
    zeus.setName("Zeus");
    Child athene = new Child();
    athene.setName("Athene");
    athene.setParent(zeus);
    Child perseus = new Child();
    perseus.setName("Perseus");
    perseus.setParent(zeus);
    zeus.getChildren().add(athene);
    zeus.getChildren().add(perseus);

    ObjectMapper mapper = new ObjectMapper();
    try {
        System.out.println("Serialized Zeus as: " + mapper.writeValueAsString(zeus));
        System.out.println("Serialized Athene as: " + mapper.writeValueAsString(athene));
        System.out.println("Serialized Perseus as: " + mapper.writeValueAsString(perseus));
    } catch (JsonProcessingException e) {
    }

这将输出以下内容:

Serialized Zeus as: {"children":[{"name":"Athene"},{"name":"Perseus"}],"name":"Zeus"}
Serialized Athene as: {"name":"Athene"}
Serialized Perseus as: {"name":"Perseus"}

这对我来说有点意外。我希望BackReference是上下文感知的,并且只能在父级未封装子级的实例中打印与父级相关的详细信息。换句话说,我希望第一行显示为我发现它,但第2行和第3行看起来更像是这样:

Serialized Athene as: {"name":"Athene","parent":{"name":"Zeus","childen":[{"name": "Athene"},{"name":"Perseus"}]}}
Serialized Perseus as: {"name":"Perseus","parent":{"name":"Zeus","childen":[{"name": "Athene"},{"name":"Perseus"}]}}

因此,在json序列化期间,只有在知道它是Child对象的成员时才会忽略父属性。

我是否在这里遗漏了一些东西,或者是否有其他方法可以解决对象序列化过程中循环依赖的问题,即使尝试直接访问也不会切断孩子对父级的所有知识? (即将其映射到Web服务时)?

0 个答案:

没有答案