问题
I have a JSON string that resembles the following:
{
"foo" : "bar",
"id" : 1,
"children":[
{
"some" : "string",
"id" : 2,
children : []
},
{
"some" : "string",
"id" : 2,
children : []
}
]
}
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);
}
}
}
回答1:
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]);
}
}
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]);
}
}
来源:https://stackoverflow.com/questions/9337536/iterate-recursively-through-deep-hashmap