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

时间:2013-03-12 14:17:28

标签: java json

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

[
    {"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”字段表示Object的唯一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":[]}
    ]},
]

有人可以帮助我吗?最好的方法是什么?

1 个答案:

答案 0 :(得分:2)

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

// 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,但很容易转换。