gpt4 book ai didi

java - 如何从 JSON 对象数组创建目录结构

转载 作者:行者123 更新时间:2023-11-30 09:25:19 25 4
gpt4 key购买 nike

我有一个像 JSONObjects(org.json.JSONObject) 的 JSONArray(org.json.JSONArray)

[
{"id":"abc", "parent_id":""},
{"id":"def", "parent_id":"abc"},
{"id":"ghi", "parent_id":""},
{"id":"jkl", "parent_id":"abc"},
{"id":"mno", "parent_id":"ghi"},
{"id":"mno", "parent_id":"def"},
]

这里的“id”字段表示对象的唯一 ID,“parent_id”表示它的父对象的 ID。我必须将此 JSONArray 转换为另一个 JSONArray,在其中我可以将元素嵌套在它们的父级(目录结构)中,例如

[
{"id":"abc", "parent_id":"","children":[
{"id":"def", "parent_id":"abc","children":[
{"id":"mno", "parent_id":"def","children":[]}
]},
{"id":"jkl", "parent_id":"abc","children":[]}
]},
{"id":"ghi", "parent_id":"","children":[
{"id":"mno", "parent_id":"ghi","children":[]}
]},
]

谁能帮我最好的方法是什么?

最佳答案

你会有这样的东西(伪代码)

// Element is { id, children }
Dictionary<String, Element> elements;

for (JSONObject obj : arr) {
if (elements.hasKey(obj.id)) {
// Maybe you need to update your element or something here
} else {
// Create your element
elements[obj.id] = new Element(obj.id);
}

// if the parent does not exist, create a shadow of the parent
// (it'll get filled in with more info above if encountered later)
if (!elements.hasKey(obj.parent)) {
elements[obj.parent] = new Element(obj.parent);
}

// Add yourself to children
elements[obj.parent].children.push(elements[obj.id]);
}

// TODO: iterate your dictionary and put it into an array, this should be straightforward
// Or if you want the root of your tree return elements[""]

我提前为没有更具体地表达歉意,但这对于您想做的任何事情都应该非常通用。而且它不是 Java,但很容易转换。

关于java - 如何从 JSON 对象数组创建目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15363734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com