使用 Java 扁平化 JSON 层次结构

发布于 2024-11-02 12:44:14 字数 1040 浏览 0 评论 0原文

因此,我有一个页面对象的层次结构,并且我正在从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

避讳 2024-11-09 12:44:14

有 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文