recursion - 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
从两者中删除,那么我又遇到了递归问题。
不知道如何得到我想要的。
解决方案
尝试添加“ JsonIgnore ”注释以防止不需要的数据从父实体进入子实体。
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Child {
private String name;
@JsonIdentityReference(alwaysAsId = true)
@ManyToOne
@JsonIgnore <- HERE
private Parent parent;
}
推荐阅读
- actions-on-google - 允许用户在 Google Home 设备上选择任何选项
- azure-devops - 如何将 YAML 中的计划触发器与本地 Azure DevOps 2019 一起使用?
- ios - ios 13 导航控件在 CNContactViewController 中向下滑动选择器以添加个人资料图片时消失?
- html - CodeMirror - 格式化 HTML 自闭标签?
- php - 如何使用 laravel 中的按钮制作正确的路线
- firebase - 为什么 Firebase 函数日志中不显示 `functions.https.HttpsError`?
- javascript - 函数被调用,但没有按预期工作。原因在哪里?
- sharepoint - 我如何复制整个 nintex 表单 + 工作流功能
- ios - 最大输入后禁用 UITextField 光标移动
- json - 如何使用密码查询语言将未嵌套的 json 数据解析到 Neo4j 数据库?