問題描述
我有一個(gè)類似于以下內(nèi)容的 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 : []
}
]
}
我對(duì)此字符串進(jìn)行 JSON 解析,然后將所有對(duì)象轉(zhuǎn)換為 HashMap,將所有數(shù)組轉(zhuǎn)換為 HashMap[].我的問題是我需要一個(gè)遞歸函數(shù)來遍歷 Java 中這個(gè) JSON 結(jié)構(gòu)的所有節(jié)點(diǎn).我怎樣才能做到這一點(diǎn)?我在想這樣的事情:
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);
}
}
}
推薦答案
假設(shè)你的一個(gè)數(shù)組里面只能有 Maps(而不是其他數(shù)組):
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 個(gè)函數(shù),你可以讓它變得更簡單
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]);
}
}
這篇關(guān)于通過深度HashMap遞歸迭代的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!