最近需要检验系统多次返回的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
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 天前 )
960b763e 2 个月前
8c391e04 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐