使用 Java 扁平化 JSON 层次结构
因此,我有一个页面对象的层次结构,并且我正在从 Postgres 系统迁移到 MongoDB,但我仍然需要支持一些传统客户端系统,这些系统需要平面 RDBMS 样式格式的数据。
如果我将它存储在 Mongo 中,我会得到类似这样的内容:
{
"id": "1",
"title": "Top Page",
"children":
[
{
"id": "2",
"title": "Page Two",
"children":
[
{
"id": "3",
"title": "Page Three",
"children": []
}
]
}
{
"id": "4",
"title": "Page Four",
"children": []
}
]
}
但我需要重新格式化它,以便客户端应用程序可以读取它。他们期望它采用这样的格式:
[
{
"id": "1",
"title": "Top Page",
"parentid": "top"
}
{
"id": "2",
"title": "Page Two",
"parentid": "1"
}
{
"id": "3",
"title": "Page Three",
"parentid": "2"
}
{
"id": "4",
"title": "Page Four",
"parentid": "1"
}
]
是否有一种简单的方法可以使用 Java 或 MongoDB 驱动程序来做到这一点?或者我只需要迭代每个对象并手动设置parentid? (其中一些层次结构相当大)。
So I have a hierarchy of page objects and I am migrating from a Postgres System over to MongoDB, but I still need to support some legacy client systems which expect data in flat RDBMS style format.
If I store it in Mongo I have something kinda like this:
{
"id": "1",
"title": "Top Page",
"children":
[
{
"id": "2",
"title": "Page Two",
"children":
[
{
"id": "3",
"title": "Page Three",
"children": []
}
]
}
{
"id": "4",
"title": "Page Four",
"children": []
}
]
}
But I need to reformat it, so the client apps can read it. And they expect it in a format like this:
[
{
"id": "1",
"title": "Top Page",
"parentid": "top"
}
{
"id": "2",
"title": "Page Two",
"parentid": "1"
}
{
"id": "3",
"title": "Page Three",
"parentid": "2"
}
{
"id": "4",
"title": "Page Four",
"parentid": "1"
}
]
Is there an easy way to do this with Java or the MongoDB driver? or will I just have to iterate thru each of the objects and set the parentids manually? (some of these hierarchies are rather large).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有 1000 种方法可以扁平化层次结构,因此我怀疑是否有现有的 API 可以做到这一点。手动执行。毕竟这是一个简单的递归方法。
There are 1000 ways to flatten a hierarchy, therefore I doubt there is an existing API to do that. Do it manually. It's a simple recursive method, after all.