package cn.com.capcloud.core.system.acl;

import cn.com.capcloud.ccui.core.common.json.JackJSONArray;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;

import java.util.*;

/**
 * @author: wangyinfeng
 * @create: 2022/1/6
 */
public class StringJsonUtils {
    public static Map<String, Object> jsonStringToMap(String jsonString) {
        Map<String, Object> map = new HashMap<>();
        JackJSONObject jsonObject = JackJSONObject.fromObject(jsonString);
        for (Object k : jsonObject.keySet()) {
            Object o = jsonObject.get(k);
            if (o instanceof JackJSONArray) {
                List<Map<String, Object>> list = new ArrayList<>();
                List<String> listStr = new ArrayList<>();
                Iterator<Object> it = ((JackJSONArray) o).iterator();
                while (it.hasNext()) {
                    Object obj = it.next();
                    if (obj instanceof String){
                        listStr.add(obj.toString());
                    }else{
                        list.add(jsonStringToMap(obj.toString()));
                    }
                }
                if(list.size()>0){
                    map.put(k.toString(), list);
                }else{
                    map.put(k.toString(), listStr);
                }
            } else if (o instanceof JackJSONObject) {
                // 如果内层是json对象的话，继续解析
                map.put(k.toString(), jsonStringToMap(o.toString()));
            } else {
                // 如果内层是普通对象的话，直接放入map中
                if (o instanceof String) {
                    map.put(k.toString(), o.toString().trim());
                } else {
                    map.put(k.toString(), o);
                }
            }
        }
        return map;
    }

}
