JsonUtil

package com.fpi.system.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;

/**
 * @author: kht
 * @date: 2021/12/23
 * @description:将json转为Map和HashMap数据结构的方法,便于获取json中的key-value值
 */
public class JsonUtil {
    
    /**
     * 将json对象转换为HashMap
     * @param json
     * @return
     */
    public static Map<String, Object> parseJsonMap(JSONObject json) {
        Map<String, Object> map = new HashMap<String, Object>(20,50);
        // 最外层解析
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            // 如果内层还是json数组的话,继续解析
            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();
                    list.add(parseJsonMap(json2));
                }
                map.put(k.toString(), list);
            } else if (v instanceof JSONObject) {
                // 如果内层是json对象的话,继续解析
                map.put(k.toString(), parseJsonMap((JSONObject) v));
            } else {
		// 如果内层是普通对象的话,直接放入map中
                map.put(k.toString(), v);
            }
        }
        return map;
    }
 
    /**将json字符串转换为Map
     * @param jsonStr
     * @return
     */
    public static Map<String, Object> parseJsonstrMap(String jsonStr) {
        JSONObject json = JSONObject.fromObject(jsonStr);
        Map<String, Object> map = parseJsonMap(json);
        return map;
    }
}

posted @ 2021-12-24 09:48  kht  阅读(60)  评论(0编辑  收藏  举报