我有一个像这样的扁平 JSON 结构,我想要一个像这样的分层 JSON 结构,
{
"root":{
"name": "world",
"children":[
{
"name": "Asia",
"children":[
{
"name": "India",
"children":[
{
"name": "WB",
"...//multiple nested children can be present"
}
]
},
{
"name": "Pakistan",
"children":[
"...//multiple nested children can be present"
]
}
]
},
{
"name": "Europe",
"children":[
{
"name": "Italy",
"children":[
{
"name":"...
...//multiple nested children can be present"
}
]
},
"...//multiple nested children can be present"
]
}
]
}
}
像上面的结构,在扁平的JSON结构中存在Root元素没有父ID的场景。
我写了一段代码,但是好像没有确切的逻辑,我也找不到逻辑,这里是代码
package jsonflattener;
import org.apache.activemq.artemis.utils.json.JSONArray;
import org.apache.activemq.artemis.utils.json.JSONException;
import org.apache.activemq.artemis.utils.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class JSONMapTest {
public static void main(String[] args) throws JSONException {
JSONArray rootJsonArray = makeJSON();
Map<String, JSONObject> idNameMap = new HashMap<>();
Map<String, Object> idNameMap2 = new HashMap<>();
JSONObject idNameMap3 = new JSONObject();
for (int i = 0; i < rootJsonArray.length(); i++) {
JSONObject data = (JSONObject) rootJsonArray.get(i);
idNameMap.put(data.getString("id"), data);
Set<String> idSet = idNameMap.keySet();
for (String id : idSet) {
JSONObject value = idNameMap.get(id);
for (Iterator keys = value.keys(); keys.hasNext(); ) {
String key = (String) keys.next();
Object pid = value.get("pid");
if (pid.equals("")) {
idNameMap2.put("root", value.get("name"));
} else if (pid.toString().equals(value.getString(id))) {
//Insert in this point
System.out.println(pid + ":" + key);
}
}
Object pid = value.get("pid");
}
}
System.out.println(idNameMap2);
}
}
请指导我如何获得所需的层次结构。