首页 > 解决方案 > Jackson:如何通过仅在子集合中添加 ID 字段来防止递归调用

问题描述

我想简化我的问题。我有一个父实体和一个子实体。

public class Parent {
  private String name;
  @OneToMany
  private List<Child> childs;
}

public class Child {
  private String name;
  @ManyToOne
  private Parent parent;
}

我想要做的是当我序列化这些实体时,它应该是这样的。

{
  "parentList": [
    {
      "id": "1",
      "name": "parent",
      "childs": [
        {
          "id": "1",
          "name": "chiled",
          "parent" : "1"
        }
      ],
    }
  ]
}

{
  "childList": [
    {
      "id": "1",
      "name": "child",
      "parent": [
        {
          "id": "1",
          "name": "parent",
          "childs": [
            {
              "id": "1",
            }
        }
      ],
    }
  ]
}

像这样:

Parent -> Child -> parentID
Child -> Parent -> childID

如果我更新我的实体,如下所示。

public class Parent {
  private String name;
  @JsonIdentityReference(alwaysAsId = true)
  @OneToMany
  private List<Child> childs;
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Child {
  private String name;
  @JsonIdentityReference(alwaysAsId = true)
  @ManyToOne
  private Parent parent;
}

有了这个设置,我几乎得到了我想要的。

Child -> Parent -> ChildID (good)
Parent -> ChildID (bad)

我需要 Parent 拥有整个 Child 实体,而 Child 实体应该只有 parentID。如果我添加@JsonIdentityInfo到两个实体,则结果如下所示:

Child -> parentID (bad)
Parent -> childID (bad)

如果我@JsonIdentityInfo从两者中删除,那么我又遇到了递归问题。

不知道如何得到我想要的。

标签: recursionserializationjacksonentity-relationshipbidirectional

解决方案


尝试添加“ JsonIgnore ”注释以防止不需要的数据从父实体进入子实体。

    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    public class Child {
      private String name;
      @JsonIdentityReference(alwaysAsId = true)
      @ManyToOne
      @JsonIgnore      <- HERE
      private Parent parent;
    }

推荐阅读