本文介紹了通過深度HashMap遞歸迭代的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個類似于以下內容的 JSON 字符串:
I have a JSON string that resembles the following:
{
"foo" : "bar",
"id" : 1,
"children":[
{
"some" : "string",
"id" : 2,
children : []
},
{
"some" : "string",
"id" : 2,
children : []
}
]
}
我對此字符串進行 JSON 解析,然后將所有對象轉換為 HashMap,將所有數組轉換為 HashMap[].我的問題是我需要一個遞歸函數來遍歷 Java 中這個 JSON 結構的所有節點.我怎樣才能做到這一點?我在想這樣的事情:
I do a JSON parse of this string, and that turns all objects into HashMaps and all arrays into HashMap[]s. My problem is I need a single recursive function to iterate through all nodes of this JSON structure in Java. How can I do this? I was thinking something like:
public HashMap findNode(boolean isArray, HashMap map, HashMap[] array){
//array stuff
if(isArray){
for(int i=0; i<array.length(); i++){
Object value = array[i];
if(value instanceof String)
System.out.println("value = "+value);
else if(value instanceof HashMap)
findNode(false, value, null);
else if(value instanceof HashMap[])
findNode(true, null, value);
}
//hashmap stuff
}else{
for(HashMap.Entry<String, Object> entry : map.entrySet()){
Object value = entry.getValue();
if(value instanceof String)
System.out.println("value = "+value);
else if(value instanceof HashMap)
findNode(false, value, null);
else if(value instanceof HashMap[])
findNode(true, null, value);
}
}
}
推薦答案
假設你的一個數組里面只能有 Maps(而不是其他數組):
Assuming you an array can only have Maps inside (and not other arrays):
public void findNode(HashMap map) {
for(HashMap.Entry<String, Object> entry : map.entrySet()){
Object value = entry.getValue();
if(value instanceof String)
System.out.println("value = "+value);
else if(value instanceof HashMap)
findNode(value);
else if(value instanceof HashMap[])
for(int i=0; i<array.length(); i++){
findNode(array[i]);
}
}
或者如果你可以使用 3 個函數,你可以讓它變得更簡單
Or you can make it even simpler if you can use 3 functions
public void findNode(HashMap map) {
for(HashMap.Entry<String, Object> entry : map.entrySet()){
findNode(entry.getValue());
}
}
public void findNode(String value) {
System.out.println("value = "+value);
}
public void findNode(HashMap[] value) {
for(int i=0; i<array.length(); i++){
findNode(array[i]);
}
}
這篇關于通過深度HashMap遞歸迭代的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!