java 扁平化输出json所有节点key/value

本章主要介绍用java实现扁平化输出json所有节点key/value(包含所有内层子节点)

1.json结构

目的输出bill_list下的datalist里的子节点key/value

2.实现代码

 public static Map<String, Object> jsonConvertMap(JSONObject json){
        Map<String, Object> map = new HashMap<>();
        if(json != null && json.size() > 0){
            for(String k : json.keySet()){
                Object v = json.get(k);
                if(v instanceof JSONArray){
                    List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
                    Iterator<Object> it = ((JSONArray)v).iterator();
                    while(it.hasNext()){
                        JSONObject json2 = (JSONObject) it.next();
                        list.add(jsonConvertMap(json2));
                    }
                    map.put(k, list);
                } else if(v instanceof JSONObject){
                    List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
                    JSONObject child = (JSONObject) v;
                    for(String stk: child.keySet()){
                        Object value = child.get(stk);
                        if(value instanceof JSONArray){
                            Iterator<Object> it = ((JSONArray)value).iterator();
                            while(it.hasNext()){
                                JSONObject json2 = (JSONObject) it.next();
                                list.add(jsonConvertMap(json2));
                            }
                        }else{
                            map.put(stk, value.toString());
                        }
                    }
                    if(list.size() > 0){
                        for(int m = 0;m<list.size();m++){
                            Map<String, Object> chMap = list.get(m);
                                for(String chKey : chMap.keySet()){
                                    map.put(chKey, chMap.get(chKey).toString());
                                }
                        }
                    }
                }else{
                    map.put(k, v);
                }
            }
        }
        return map;
    }

 

posted @ 2018-06-20 17:11  春风十里的情  阅读(3483)  评论(0编辑  收藏  举报