我需要从JSON构建一个树。对于每个restProjectLevel,JSON结构都会读取:restProjectLevels我有一个id = level。 sequenceNr = root或child。对于每个restProject:restProjects我有一个id = projectId和一个projectIdHook =附加的projectId。
我认为JSON数据最能解释它。
{
"id": 3,
"description": "New Project Plan",
"restProjectLevels": [
{
"id": 19,
"sequenceNr": 0,
"restProjects": [
{
"id": 28,
"projectName": "Project A",
"description": "",
"projectLevelId": 19,
"projectIdHook": 0,
"restProjectProcesses": []
},
{
"id": 29,
"projectName": "Project B",
"description": "",
"projectLevelId": 19,
"projectIdHook": 0,
"restProjectProcesses": []
},
{
"id": 30,
"projectName": "Project C",
"description": "",
"projectLevelId": 19,
"projectIdHook": 0,
"restProjectProcesses": []
},
{
"id": 41,
"projectName": "New",
"description": "",
"projectLevelId": 19,
"projectIdHook": 0,
"restProjectProcesses": []
}
]
},
{
"id": 20,
"sequenceNr": 1,
"restProjects": [
{
"id": 31,
"projectName": "Project A.1",
"description": "",
"projectLevelId": 20,
"projectIdHook": 28,
"restProjectProcesses": []
},
{
"id": 33,
"projectName": "Project B.1",
"description": "",
"projectLevelId": 20,
"projectIdHook": 29,
"restProjectProcesses": []
},
{
"id": 35,
"projectName": "Project C.1",
"description": "",
"projectLevelId": 20,
"projectIdHook": 30,
"restProjectProcesses": []
}
]
},
{
"id": 21,
"sequenceNr": 2,
"restProjects": [
{
"id": 32,
"projectName": "Project A.2",
"description": "",
"projectLevelId": 21,
"projectIdHook": 31,
"restProjectProcesses": []
},
{
"id": 36,
"projectName": "Project C.2",
"description": "",
"projectLevelId": 21,
"projectIdHook": 35,
"restProjectProcesses": []
}
]
},
{
"id": 22,
"sequenceNr": 3,
"restProjects": [
{
"id": 34,
"projectName": "Projet B.4",
"description": "",
"projectLevelId": 22,
"projectIdHook": 33,
"restProjectProcesses": []
},
{
"id": 37,
"projectName": "Project C.3",
"description": "",
"projectLevelId": 22,
"projectIdHook": 36,
"restProjectProcesses": []
}
]
},
{
"id": 23,
"sequenceNr": 4,
"restProjects": []
}
]
}
答案 0 :(得分:0)
确定解决了这个问题!不是最优雅的解决方案,但它有效...
for(RestProjectLevel projectLevel: projectLevelList) {
if(projectLevel.getSequenceNr() == 0) {
for(RestProject project : projectLevel.getRestProjects()) {
restParentNode = new RestParentNode();
traverse(sortedRestProjects, project, restParentNode);
restTree.nodes.add(restParentNode);
}
}
}
private void traverse(List<RestProject> restProjects, RestProject project, RestParentNode restParentNode) {
for (RestProject restProject : restProjects) {
if(project.getId() == restProject.getProjectIdHook() || project.getId() == restProject.getId()) {
String projectName = restProject.getProjectName();
if(hasNode(projectName)) {
continue;
} else {
RestNode restNode = new RestNode();
restNode.nodes.add(restProject);
restParentNode.nodes.add(restNode);
traverse(restProjects, restProject, restParentNode);
}
}
}
}
谢谢!