简体   繁体   中英

Flattening a JSON hierachy using Java

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM