我有一个类似于以下内容的 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模板网!