嵌套(任意层)JSON解析转换为Map

最近需要检验系统多次返回的json结果是否相同,以保证系统升级后的功能一致,所以产生了编写json转换程序的需求。

由于小弟编程能力尚浅,有些特殊情况的转换没能考虑好,希望各位可以提出,或者贴出更完善的解析程序供大家分享,先在此处抛砖引玉了。

以下程序用于把多层嵌套的json字符串转换为平层的Map,以方便在后续的测试程序中对比结果。

源代码:


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

import java.util.*;
import java.util.Map.Entry;

/**
 * Created by chenyuzhi on 17-8-12.
 */
public class JsonParseUtil {



    public static String checkFormat(String str){
        String _str = str.trim();
        if(_str.startsWith("[") && _str.endsWith("]")){
            return  _str.substring(1,_str.length()-1);
        }
        return  _str;
    }

    /**
     * 打印Map中的数据
     * @param map
     */
    public static void printJsonMap(Map map){
        Set entrySet = map.entrySet();
        Iterator<Map.Entry<String, Object>> it = entrySet.iterator();
        //最外层提取
        while(it.hasNext()){
            Map.Entry<String, Object> e = it.next();
            System.out.println("Key 值:"+e.getKey()+"     Value 值:"+e.getValue());
        }
    }



    /**
     * JSON 类型的字符串转换成 Map
     */
    public static void parseJSON2Map(Map jsonMap,String jsonStr,String parentKey){
        //字符串转换成JSON对象
        JSONObject json = JSONObject.fromObject(jsonStr);
        //最外层JSON解析
        for(Object k : json.keySet()){
            //JSONObject 实际上相当于一个Map集合,所以我们可以通过Key值获取Value
            Object v = json.get(k);
            //构造一个包含上层keyName的完整keyName
            String fullKey = (null == parentKey || parentKey.trim().equals("") ? k.toString() : parentKey + "." + k);

            if(v instanceof JSONArray){
                 //如果内层还是数组的话,继续解析
                Iterator it = ((JSONArray) v).iterator();
                while(it.hasNext()){
                    JSONObject json2 = (JSONObject)it.next();
                    parseJSON2Map(jsonMap,json2.toString(),fullKey);
                }
            } else if(isNested(v)){
                parseJSON2Map(jsonMap,v.toString(),fullKey);
            }
            else{
                jsonMap.put(fullKey, v);
            }
        }
    }

    public static boolean isNested(Object jsonObj){

        return jsonObj.toString().contains("{");
    }

    public static void println(Object str){
        System.out.println(str);
    }
}

测试程序:

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

import java.util.*;
import java.util.Map.Entry;

/**
 * Created by chenyuzhi on 17-8-12.
 */
public class JsonParseUtil {
    public static void main(String[] args) throws Exception {
        JsonParseUtil jsonParseUtil = new JsonParseUtil();
        jsonParseUtil.test();
    }



    public void test(){
        //JSON类型的字符串
        String strJson = "{a:1,b:2,c:3,d:[{a1:11,a2:22,a3:33},{a1:{a2:222,a3:333}}]}";

        Map jsonMap = new HashMap();
        parseJSON2Map(jsonMap,checkFormat(strJson),null);
        printJsonMap(jsonMap);
    }
}

测试结果:

Key 值:a     Value 值:1
Key 值:b     Value 值:2
Key 值:d.a3     Value 值:33
Key 值:c     Value 值:3
Key 值:d.a1     Value 值:11
Key 值:d.a2     Value 值:22
Key 值:d.a1.a3     Value 值:333
Key 值:d.a1.a2     Value 值:222
  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值