java解析json转Map

java解析json转Map前段时间在做json报文处理的时候,写了一个针对不同格式json转map的处理工具方法,总结记录如下:1、单节点单层级、单节点多层级json转mapimportjava.util.ArrayList;importjava.util.HashMap;importjava.util.Iterator;importjava.util.List;importjava.util.Map;i

大家好,又见面了,我是你们的朋友全栈君。

前段时间在做json报文处理的时候,写了一个针对不同格式json转map的处理工具方法,总结记录如下:

1、单节点单层级、单节点多层级json转map

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.json.JSONTokener;

/** * 功能: * 1、将单/多层级的Json字符串解析为Map格式 * 2、将Map格式的数据封装成Json * * 避免字符串中有特殊字符而出现的错误 * @author lmb * @version 1.0 * @date 2017-06-01 */
public class JSONUtils { 
   

    private final static String regex = "\"([^\\\" ]+?)\":";

    /** * 一个方法解析多层json数据 json + 正则 + 递归 * @param jsonStr * @return */
    public static Object jsonParse(final String jsonStr) {
        if (jsonStr == null) throw new NullPointerException("JsonString shouldn't be null");
        try {
            if (isJsonObject(jsonStr)) {
                final Pattern pattern = Pattern.compile(regex);
                final Matcher matcher = pattern.matcher(jsonStr);
                final Map<String, Object> map = new HashMap<String, Object>();
                final JSONObject jsonObject = new JSONObject(jsonStr);
// System.out.println("jsonStr = " + jsonStr);
// System.out.println("jsonObject = " + jsonObject);
                try {
                    for (; matcher.find(); ) {
                        String groupName = matcher.group(1);
                        Object obj = jsonObject.opt(groupName);
                        if (isJsonObject(obj+"") || isJsonArray(obj+"")) {
                            matcher.region(matcher.end() + (obj+"").replace("\\", "").length(), matcher.regionEnd());
                            map.put(groupName, jsonParse(obj+""));
                        } else {
                            map.put(groupName, obj+"");
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }
                return map;
            } else if (isJsonArray(jsonStr)) {
                List<Object> list = new ArrayList<Object>();
                try {
                    JSONArray jsonArray = new JSONArray(jsonStr);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        Object object = jsonArray.opt(i);
                        list.add(jsonParse(object+""));
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }
                return list;
            } 
        } catch (Exception e) {
            // TODO: handle exception
        }
        return jsonStr;
    }

    /** * To determine whether a string is JsonObject {@link org.json.JSONObject} * @param jsonStr {@link java.lang.String} * @return boolean */
    private static boolean isJsonObject(final String jsonStr) {
        if (jsonStr == null) return false;
        return Pattern.matches("^\\{.*\\}$", jsonStr.trim());
    }

    /** * To determine whether a string is JsonArray {@link org.json.JSONArray}; * @param jsonStr {@link java.lang.String} * @return boolean */
    private static boolean isJsonArray(final String jsonStr) {
        if (jsonStr == null) return false;
        return Pattern.matches("^\\[.*\\]$", jsonStr.trim());
    }

    /** * 将对象封装为json字符串 (json + 递归) * @param obj 参数应为{@link java.util.Map} 或者 {@link java.util.List} * @return */
    @SuppressWarnings("unchecked")
    public static Object jsonEnclose(Object obj) {
        try {
            if (obj instanceof Map) {   //如果是Map则转换为JsonObject
                Map<String, Object> map = (Map<String, Object>)obj;
                Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
                JSONStringer jsonStringer = (JSONStringer) new JSONStringer().object();
                while (iterator.hasNext()) {
                    Entry<String, Object> entry = iterator.next();
                    jsonStringer.key(entry.getKey()).value(jsonEnclose(entry.getValue()));
                }
                JSONObject jsonObject = new JSONObject(new JSONTokener(jsonStringer.endObject().toString()));
                return jsonObject;
            } else if (obj instanceof List) {  //如果是List则转换为JsonArray
                List<Object> list = (List<Object>)obj;
                JSONStringer jsonStringer = (JSONStringer) new JSONStringer().array();
                for (int i = 0; i < list.size(); i++) {
                    jsonStringer.value(jsonEnclose(list.get(i)));
                }
                JSONArray jsonArray = new JSONArray(new JSONTokener(jsonStringer.endArray().toString()));
                return jsonArray;
            } else {
                return obj;
            }
        } catch (Exception e) {
            // TODO: handle exception
            return e.getMessage();
        }
    }


    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        /* * 解析时使用示例 */
        String jsonStr1 = "{\"ContractRoot\":{" +
                " \"tcpCont\":{" +
                " \"ActionCode\":\"1\"," +
                " \"Response\":{" +
                " \"RspCode\":\"9002\"," +
                " \"RspDesc\":\"TransactionID超出长度约束\"," +
                " \"RspType\":\"9\"" +
                " }," +
                " \"RspTime\":\"20170527144416\"," +
                " \"TransactionID\":\"74201705281800202798\"" +
                " }" +
                " }" +
                " }";
        String jsonStr2 = "{\"ContractRoot\":\"9002\"," +
                " \"RspDesc\":\"TransactionID超出长度约束\"," +
                " \"RspType\":\"9\"," +
                " \"RspTime\":\"20170527144416\"," +
                " \"TransactionID\":\"74201705281800202798\"" +
                " }";
        Object object = jsonParse(jsonStr1);
        System.out.println(object);
        Map resultMap = new HashMap();
        boolean flag = true;
        while(flag){
            flag = false;
            if (object instanceof String) {
               System.out.println("string = " + object.toString());
            } else if (object instanceof Map) {
                HashMap<String, Object> map = (HashMap<String, Object>)object;
                Iterator<Entry<String, Object>>  iterator = map.entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry<String, Object> entry = iterator.next();
                    if (entry.getValue() instanceof Map) {
                         object = entry.getValue();
                         flag = true;
                    } else {
                         resultMap.put(entry.getKey(),entry.getValue().toString());
                    }
                }
            } else if (object instanceof List) {
  
  //list未测试
                System.out.println("list = " + object.toString());
            }
        }
         System.out.println("resultMap : " + resultMap);
         /** * resultMap : {TransactionID=74201705281800202798, RspType=9, RspCode=9002, ActionCode=1, RspTime=20170527144416, RspDesc=TransactionID超出长度约束} * resultMap : {TransactionID=74201705281800202798, RspType=9, RspTime=20170527144416, RspDesc=TransactionID超出长度约束, ContractRoot=9002} */

        /* * 封装时使用示例 */
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("returnCode", "0");
        map.put("returnMsg", "成功");
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); 
        Map<String, Object> listMap = new HashMap<String, Object>();
        listMap.put("test", "测试");
        listMap.put("fucp", "fucp");
        list.add(listMap);
        list.add(listMap);
        map.put("returnStatus", list);
        System.out.println("map : " + map);
        System.out.println("json : " + jsonEnclose(map).toString());
        /* * 封装结果 * map : {returnCode=0, returnMsg=成功, returnStatus=[{test=测试, fucp=fucp}, {test=测试, fucp=fucp}]} * json : {"returnCode":"0","returnMsg":"成功","returnStatus":[{"test":"测试","fucp":"fucp"},{"test":"测试","fucp":"fucp"}]} */
    }

}

2、多结点多层级json转map

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.simpleproxy.dataparse.json.JsonUtil;

/** * 功能:通过属性文件处理JSON报文 * @author lmb * @version 1.0 * @date 2017-6-5 */
public class ParseJSONByPropertyFile { 
   

    /** * 根据json报文和结点全路径获取相应的节点值 * @param respStr json报文 * @param nodePath 要获取的字段在json中的节点全路径(用">"分割) * @return */
    @SuppressWarnings("unchecked")
    public static List<Map<String,Object>> json2MapbyHandler(String respStr,String nodePath){

        List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        Map map = JsonUtil.parseJSON2Map(respStr);
        String[] strArray = nodePath.split(">");
        String key = null;
        Object value = null;
        for (int i = 0; i < strArray.length; i++) {
            if (map.get(strArray[i]) instanceof List) {
                if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) {
                    Map<String,Object> mapList = map;
                    if (((List<Map<String,Object>>)mapList.get(strArray[i])).size() > 0) {
                        for (int j = 0; j < ((List<Map<String,Object>>)mapList.get(strArray[i])).size(); j++) {
                            Map<String,Object> mapj = new HashMap<String,Object>();
                            map = ((List<Map<String,Object>>)mapList.get(strArray[i])).get(j);
                            mapj.put(strArray[i+1],map.get(strArray[i + 1]));
                            resultList.add(mapj);
                        }
                    }
                }
                break;
            }else{
                if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) {
                    map = JsonUtil.parseJSON2Map(map.get(strArray[i]).toString());
                }else{
                    Map<String,Object> resultMap = new HashMap<String,Object>();
                    resultMap.put(strArray[i],map.get(strArray[i]));
                    resultList.add(resultMap);
                }
            }
        }
        return resultList;      
    }

    /** * 根据json报文和结点获取相应的值 * @param respStr json报文 * @param listNode 要获取的字段在json中的节点路径(用">"分割) * @return */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static List<Map<String,Object>> json2ListbyHandler(String respStr,String listNode){

        List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        Double d = new Double("0.0000");
        Map map = JsonUtil.parseJSON2Map(respStr);
        String[] strArray = listNode.split(">");
        String key = null;
        Object value = null;
        for (int i = 0; i < strArray.length; i++) {
            if (map.get(strArray[i]) instanceof List) {
                if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) {
                    Map<String,Object> mapList = map;
                    if (((List<Map<String,Object>>)mapList.get(strArray[i])).size() > 0) {
                        for (int j = 0; j < ((List<Map<String,Object>>)mapList.get(strArray[i])).size(); j++) {
                            Map mapj = new HashMap();
                            map = ((List<Map<String,Object>>)mapList.get(strArray[i])).get(j);
                            mapj.put(strArray[i+1],map.get(strArray[i + 1])+"");//listNode
                            resultList.add(mapj);
                        }
                    }
                }
                break;
            }else{
                if (i < strArray.length - 1 && null != map.get(strArray[i]) && "" != map.get(strArray[i])) {
                    map = JsonUtil.parseJSON2Map(map.get(strArray[i]).toString());
                }else{
                    Map<String,Object> resultMap = new HashMap<String,Object>();
                    resultMap.put(strArray[i],map.get(strArray[i])+"");//listNode
                    resultList.add(resultMap);
                }
            }
        }
        System.out.println(resultList);
        return resultList;      
    }

    /** * 根据节点的list集合将json报文组装成多包体list * @param nodeList * @param respXml * @return */
    public static List<Map<String,Object>> str2ListbyHandler(List<String> nodeList,String respStr){

        Map<String,Object> resultMap = new HashMap<String,Object>();
        List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        Map<String,Object> commonMap = new HashMap<String,Object>();
        int flag = 0;
        if (null != nodeList && nodeList.size() > 0) {
            for(String field : nodeList){
                List<Map<String,Object>> thirdList = new ArrayList<Map<String,Object>>();
                thirdList = json2ListbyHandler(respStr,field);
                if (thirdList.size() > 0) {
                    if (thirdList.size() < 2) {
  
  //公共参数
                        commonMap.putAll(thirdList.get(0));
                    }else{
  
  //某节点下为list集合
                        if (flag == 0) {
                            resultList = thirdList;
                        }
                        for (int i = 0; i < thirdList.size(); i++) {
                            resultList.get(i).putAll(thirdList.get(i));
                        }
                        flag++;
                    }
                }
            }
        }
        if (resultList.size() == 0) {
            resultList.add(commonMap);
        }else{
            for (int i = 0; i < resultList.size(); i++) {
                resultList.get(i).putAll(commonMap);
            }
        }
        System.out.println("resultList >> " + resultList);
        return resultList;
    }

    public static void main(String[] args) {
        String str = "{\"ROOT\":{" +
                " \"HEADER\":{" +
                " \"ROUTING\":{" +
                " \"ROUTE_KEY\":\"qqq\"," +
                " \"ROUTE_VALUE\":\"ccc\"" +
                " }," +
                " \"DB_ID\":\"USA\"," +
                " \"ENV_ID\":\"bbb\"," +
                " \"KEEP_LIVE\":\"yes\"," +
                " \"PROVINCE_GROUP\":\"\"," +
                " \"POOL_ID\":\"11\"," +
                " \"TENANT_ID\":\"USA\"," +
                " \"LANG\":\"en_US\"" +
                " }," +
                " \"BODY\":{" +
                " \"RETURN_CODE\":\"10111109000000003\"," +
                " \"RETURN_MSG\":\"Failed to get user info!\"," +
                " \"USER_MSG\":\"取用户信息错误!\"," +
                " \"DETAIL_MSG\":\"error\"," +
                " \"PROMPT_MSG\":\"取用户信息错误!\"," +
                " \"RUN_IP\":\"192.168.50.112\"," +
                " \"OUT_DATA\":{" +
                " \"FREE_INFO\"= [" +
                " {\"BUSI_CODE\"= \"EUR_CUEasy £ 36(UK-CHINA)\"," +
                " \"FAV_TYPE\"= \"ECH0\"," +
                " \"PRIORITY\"= \"0\"," +
                " \"PROD_PRCID\"= \"10000000017607\"," +
                " \"PROD_PRC_NAME\"= \"CUEasy £ 36(UK-CHINA)\"," +
                " \"TOTAL\"= \"2000\"," +
                " \"UNIT\"= \"3\"," +
                " \"UNIT_NAME\"= \"Minute\"," +
                " \"USED\"= \"0\"" +
                " }," +
                " {\"BUSI_CODE\"= \"USA_CUEasy £ 36(UK-CHINA)\"," +
                " \"FAV_TYPE\"= \"ECH0\"," +
                " \"PRIORITY\"= \"0\"," +
                " \"PROD_PRCID\"= \"10000000017607\"," +
                " \"PROD_PRC_NAME\"= \"CUEasy £ 36(UK-CHINA)\"," +
                " \"TOTAL\"= \"1000\"," +
                " \"UNIT\"= \"1\"," +
                " \"UNIT_NAME\"= \"piece\"," +
                " \"USED\"= \"0\"" +
                " }" +
                " ]" +
                " }" +
                " }" +
                " }" +
                " }" +
                "}";
        System.out.println("********从json中将单个节点的值查找出来*********************");
        String nodePath = "ROOT>BODY>OUT_DATA>FREE_INFO>BUSI_CODE";
        System.out.println(json2MapbyHandler(str,nodePath));
        /* * [{BUSI_CODE=EUR_CUEasy £ 36(UK-CHINA)}, {BUSI_CODE=USA_CUEasy £ 36(UK-CHINA)}] */
        System.out.println("***************从json中将节点集合中的所有节点值都查找出来***********************");
        List<String> nodeList = new ArrayList<String>();
        nodeList.add("ROOT>BODY>OUT_DATA>FREE_INFO>FAV_TYPE");
        nodeList.add("ROOT>BODY>OUT_DATA>FREE_INFO>PRIORITY");
        nodeList.add("ROOT>BODY>OUT_DATA>FREE_INFO>PROD_PRCID");
        nodeList.add("ROOT>BODY>OUT_DATA>FREE_INFO>PROD_PRC_NAME");
        nodeList.add("ROOT>BODY>OUT_DATA>FREE_INFO>TOTAL");
        nodeList.add("ROOT>BODY>OUT_DATA>FREE_INFO>UNIT");
        str2ListbyHandler(nodeList,str);
        /* * [{FAV_TYPE=ECH0, UNIT=3, PROD_PRC_NAME=CUEasy £ 36(UK-CHINA), PRIORITY=0, TOTAL=2000, PROD_PRCID=10000000017607}, * {FAV_TYPE=ECH0, UNIT=1, PROD_PRC_NAME=CUEasy £ 36(UK-CHINA), PRIORITY=0, TOTAL=1000, PROD_PRCID=10000000017607}] */
    }
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/148305.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号