package com.platform.common.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Map工具类
 */
public class MapUtils extends HashMap<String, Object> {

    @Override
    public MapUtils put(String key, Object value) {
        super.put(key, value);
        return this;
    }
    public static Map<String, Object> json2map(String jsonStr) {
    	Map<String, Object> map = new HashMap<>();
    	jsonStr = jsonStr.replaceAll("null", "\"\"");
        if(StringUtils.isNotBlank(jsonStr)){
            //最外层解析
            JSONObject json = JSONObject.fromObject(jsonStr);
            if(json==null || json.isNullObject()){
            	return null;
            }
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                //如果内层还是数组的话，继续解析
                if((v instanceof JSONArray)) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<JSONObject> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = it.next();
                        Map<String, Object> m = json2map(json2.toString());
                        if(m!=null && m.size()>0){
                        	list.add(m);
                        }
                    }
                    map.put(k.toString(), list);
            	}else{
                	map.put(k.toString(), (v==null || v.equals(null)) ? "":v);
                }
            }
            return map;
        }else{
            return null;
        }
  
    }
}
