java - Jackson @JsonIdentityInfo 和 @JsonIdentityReference 和自定义序列化
问题描述
我正在使用杰克逊在 JSON 中序列化我的对象。该对象是 JPA 实体,因此具有循环关联。
所以,我有这个简单的 POJO:
private static class Bean {
String id;
String description;
@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id", scope = Bean.class)
@JsonIdentityReference(alwaysAsId = false)
Bean ref;
}
我序列化了这个实例:
Bean a = new Bean();
a.id = "1";
a.description = "The first";
Bean b = new Bean();
b.id = "2";
b.description = "The second";
Bean c = new Bean();
c.id = "3";
b.description = "The last one";
// setup refs
a.ref = b;
b.ref = c;
c.ref = a; // circular
最后我需要这个 JSON:
{
"id": "1",
"description" : "The first",
"ref": {
"id" : "2",
"description" : "The second",
"ref": {
"id" : "3",
"description" : "The last one"
"ref" : {
"id" : "1"
}
}
}
}
我需要循环引用仅序列化“id”属性(并省略其他属性),并且“ref”必须继续是 object。
这是可能的?
解决方案
只需将 ref 设置为没有另一个 ref 的对象。
c.ref = new Bean();
c.ref.id = a.id;
推荐阅读
- python - TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“QLineEdit”
- javascript - 功能无效,因为出现 React Child 警告并且无法显示我的图像
- python-2.7 - 如何从邮递员执行python脚本?
- javascript - 单个列搜索不适用于 DataTables
- java - 从数据库序列中获取下一个值
- php - 保存 POST 数据以备后用
- c# - 如何连接到数据库?
- php - 拉取json解码数组结果
- python - 无法使用 python-kafka 消费消息
- tsql - 使用“GOTO”跳过 TSQL 中脚本的特定部分