java 扁平化輸出json全部節點key/value

本章主要介紹用java實現扁平化輸出json全部節點key/value(包含全部內層子節點)java

1.json結構json

目的輸出bill_list下的datalist裏的子節點key/valueblog

2.實現代碼get

 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;
    }
相關文章
相關標籤/搜索