欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Json字符串內(nèi)容比較超實(shí)用教程

 更新時(shí)間:2023年09月07日 09:17:02   作者:mossGao  
這篇文章主要介紹了Json字符串內(nèi)容比較-超實(shí)用版,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

背景

之前有類似接口diff對比,數(shù)據(jù)對比的測試需求,涉及到j(luò)son格式的數(shù)據(jù)對比,調(diào)研了幾個(gè)大神們分享的代碼,選了一個(gè)最符合自己需求的研究了下。

說明

這個(gè)對比方法,支持JsonObject和JsonArray類型的數(shù)據(jù)對比,支持:

  • 深度的對比:list變化(個(gè)數(shù)、內(nèi)容)、層級結(jié)構(gòu)變化
  • 字段的對比:新增、修改、刪除數(shù)據(jù)可察覺,能找到對應(yīng)的舊數(shù)據(jù)
  • 支持特定字段忽略對比

輸出的對比結(jié)果格式為:

源碼分為JsonCompareUtils, JsonAndMapSortUtils兩個(gè)類,對比入口是compareTwoJson方法

核心邏輯在JsonCompareUtils類中,JsonAndMapSortUtils主要做過程中的數(shù)據(jù)排序功能,相對獨(dú)立。

 上源碼:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;
public class JsonCompareUtils {
    //標(biāo)志位:對json報(bào)文中含有JsonArray類型的數(shù)據(jù)是否進(jìn)行排序
    private static boolean isSort;
    private Map<String, Object> oldJsonToMap = new LinkedHashMap<>();
    private Map<String, Object> newJsonToMap = new LinkedHashMap<>();
    //每一個(gè)實(shí)體里的排序字段
    private static Map<String, String> filedNameMap = new HashMap<>();
    static {
        filedNameMap.put("ojb1", "id");
        filedNameMap.put("ojb2", "id");
    }
    //可以跳過比對的字段
    private static String[] skipCompareFiledNameMap = {"createTime"};
    /**
     * 兩json報(bào)文比對入口
     *
     * @param oldJsonStr
     * @param newJsonStr
     * @return
     */
    public String compare2Json(String oldJsonStr, String newJsonStr) {
        /**
         * 遞歸遍歷json對象所有的key-value,以map形式的path:value進(jìn)行存儲(chǔ)
         * 然后對兩個(gè)map進(jìn)行比較
         */
        convertJsonToMap(JSON.parseObject(oldJsonStr), "", false);
        convertJsonToMap(JSON.parseObject(newJsonStr), "", true);
        //獲取比較結(jié)果
        Map<String, Object> differenceMap = compareTwoMaps(oldJsonToMap, newJsonToMap);
        String diffJsonResult = convertMapToJson(differenceMap);
        return diffJsonResult;
    }
    /**
     * 將json數(shù)據(jù)轉(zhuǎn)換為map存儲(chǔ)--用于后續(xù)比較map
     *
     * @param json
     * @param root
     * @param isNew 區(qū)別新舊報(bào)文
     */
    private void convertJsonToMap(Object json, String root, boolean isNew) {
        if (json instanceof JSONObject) {
            JSONObject jsonObject = ((JSONObject) json);
            Iterator iterator = jsonObject.keySet().iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = jsonObject.get(key);
                String newRoot = "".equals(root) ? key + "" : root + "." + key;
                fillInResultMap(value, newRoot, isNew);
            }
        } else if (json instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) json;
            //將jsonArray進(jìn)行排序
            if (isSort) {
                //需要排序
                String sortEntityName = root.substring(root.lastIndexOf(".") + 1);
                //需要排序 獲取排序字段
                String sortFiledName = filedNameMap.get(sortEntityName);
                if (!StringUtils.isEmpty(sortFiledName)) {
                    jsonArray = JsonAndMapSortUtils.jsonArrayToSort(jsonArray, sortFiledName, true);
                }
            }
            final JSONArray jsonArray1 = jsonArray;
            Stream.iterate(0, integer -> integer + 1).limit(jsonArray1.size()).forEach(index -> {
                Object value = jsonArray1.get(index);
                String newRoot = "".equals(root) ? "[" + index + "]" : root + ".[" + index + "]";
                fillInResultMap(value, newRoot, isNew);
            });
        }
    }
    /**
     * 封裝json轉(zhuǎn)map后的數(shù)據(jù)
     *
     * @param value
     * @param newRoot
     * @param isNew   區(qū)別新舊json
     */
    public void fillInResultMap(Object value, String newRoot, boolean isNew) {
        if (value instanceof JSONObject || value instanceof JSONArray) {
            convertJsonToMap(value, newRoot, isNew);
        } else {
            //設(shè)置跳過比對的字段,直接不裝入map
            boolean check = ArrayUtils.contains(JsonCompareUtils.skipCompareFiledNameMap, newRoot);
            if (!check){
                if (!isNew) {
                    oldJsonToMap.put(newRoot, value);
                } else {
                    newJsonToMap.put(newRoot, value);
                }
            }
        }
    }
    /**
     * 比較兩個(gè)map,將不同的數(shù)據(jù)以map形式存儲(chǔ)并返回
     *
     * @param oldJsonMap
     * @param newJsonMap
     * @return
     */
    private Map<String, Object> compareTwoMaps(Map<String, Object> oldJsonMap, Map<String, Object> newJsonMap) {
        //1.將newJsonMap的不同數(shù)據(jù)裝進(jìn)oldJsonMap,同時(shí)刪除oldJsonMap中與newJsonMap相同的數(shù)據(jù)
        newJsonMap.forEach((k, v) -> {
            Map<String, Object> differenceMap = new HashMap<>();
            if (oldJsonMap.containsKey(k)) {
                Object oldValue = oldJsonMap.get(k);
                if (v.equals(oldValue)) {
                    oldJsonMap.remove(k);
                } else {
                    differenceMap.put("oldValue", oldValue);
                    differenceMap.put("newValue", v);
                    oldJsonMap.put(k, differenceMap);
                }
            } else {
                differenceMap.put("oldValue", "no exists " + k);
                differenceMap.put("newValue", v);
                oldJsonMap.put(k, differenceMap);
            }
        });
        //2.統(tǒng)一oldJsonMap中newMap不存在的數(shù)據(jù)的數(shù)據(jù)結(jié)構(gòu),便于解析
        oldJsonMap.forEach((k, v) -> {
            if (!(v instanceof Map)) {
                Map<String, Object> differenceMap = new HashMap<>();
                differenceMap.put("oldValue", v);
                differenceMap.put("newValue", "no exists " + k);
                oldJsonMap.put(k, differenceMap);
            }
        });
        return oldJsonMap;
    }
    /**
     * 將已經(jīng)找出不同數(shù)據(jù)的map根據(jù)key的層級結(jié)構(gòu)封裝成json返回
     *
     * @param map
     * @return
     */
    private String convertMapToJson(Map<String, Object> map) {
        JSONObject resultJSONObject = new JSONObject();
        for (Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<String, Object> item = it.next();
            String key = item.getKey();
            Object value = item.getValue();
            String[] paths = key.split("\\.");
            int i = 0;
            //用於深度標(biāo)識對象
            Object remarkObject = null;
            int indexAll = paths.length - 1;
            while (i <= paths.length - 1) {
                String path = paths[i];
                if (i == 0) {
                    //初始化對象標(biāo)識
                    if (resultJSONObject.containsKey(path)) {
                        remarkObject = resultJSONObject.get(path);
                    } else {
                        if (indexAll > i) {
                            if (paths[i + 1].matches("\\[[0-9]+\\]")) {
                                remarkObject = new JSONArray();
                            } else {
                                remarkObject = new JSONObject();
                            }
                            resultJSONObject.put(path, remarkObject);
                        } else {
                            resultJSONObject.put(path, value);
                        }
                    }
                    i++;
                    continue;
                }
                //匹配集合對象
                if (path.matches("\\[[0-9]+\\]")) {
                    int startIndex = path.lastIndexOf("[");
                    int endIndext = path.lastIndexOf("]");
                    int index = Integer.parseInt(path.substring(startIndex + 1, endIndext));
                    if (indexAll > i) {
                        if (paths[i + 1].matches("\\[[0-9]+\\]")) {
                            while (((JSONArray) remarkObject).size() <= index) {
                                if (((JSONArray) remarkObject).size() == index) {
                                    ((JSONArray) remarkObject).add(index, new JSONArray());
                                } else {
                                    ((JSONArray) remarkObject).add(null);
                                }
                            }
                        } else {
                            while (((JSONArray) remarkObject).size() <= index) {
                                if (((JSONArray) remarkObject).size() == index) {
                                    ((JSONArray) remarkObject).add(index, new JSONObject());
                                } else {
                                    ((JSONArray) remarkObject).add(null);
                                }
                            }
                        }
                        remarkObject = ((JSONArray) remarkObject).get(index);
                    } else {
                        while (((JSONArray) remarkObject).size() <= index) {
                            if (((JSONArray) remarkObject).size() == index) {
                                ((JSONArray) remarkObject).add(index, value);
                            } else {
                                ((JSONArray) remarkObject).add(null);
                            }
                        }
                    }
                } else {
                    if (indexAll > i) {
                        if (paths[i + 1].matches("\\[[0-9]+\\]")) {
                            if (!((JSONObject) remarkObject).containsKey(path)) {
                                ((JSONObject) remarkObject).put(path, new JSONArray());
                            }
                        } else {
                            if (!((JSONObject) remarkObject).containsKey(path)) {
                                ((JSONObject) remarkObject).put(path, new JSONObject());
                            }
                        }
                        remarkObject = ((JSONObject) remarkObject).get(path);
                    } else {
                        ((JSONObject) remarkObject).put(path, value);
                    }
                }
                i++;
            }
        }
        return JSON.toJSONString(resultJSONObject);
    }
    public boolean isSort() {
        return isSort;
    }
    public void setSort(boolean sort) {
        isSort = sort;
    }
    public static void main(String[] args) {
        String oldStr = "{\"abilityLevel\":\"2020101240000000000002\",\"activityId\":\"202208301413310000412\",\"addLibTime\":1662083360000,\"ansKnowModelIds\":\"1#201812051814150000475\",\"answer\":\"AB\",\"ascriptionItemLib\":\"0\",\"attributeList\":[{\"content\":\"<p>A</p>\",\"id\":\"202209020949170005783\",\"itemId\":\"202209020949150001521\",\"knowModelRelId\":\"201812051814150000475\",\"name\":\"A\",\"sort\":1,\"type\":\"option\"},{\"content\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">B</p>\",\"id\":\"202209020949170005784\",\"itemId\":\"202209020949150001521\",\"name\":\"B\",\"sort\":2,\"type\":\"option\"},{\"content\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">C</p>\",\"id\":\"202209020949170005785\",\"itemId\":\"202209020949150001521\",\"name\":\"C\",\"sort\":3,\"type\":\"option\"},{\"content\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">D</p>\",\"id\":\"202209020949170005786\",\"itemId\":\"202209020949150001521\",\"name\":\"D\",\"sort\":4,\"type\":\"option\"},{\"content\":\"11\",\"createTime\":1662083368000,\"createTimeString\":\"2022-09-02 09:49:28\",\"creater\":\"10001\",\"id\":\"202209020949170005787\",\"itemId\":\"202209020949150001521\",\"name\":\"大綱依據(jù)\",\"searchFlag\":\"1\",\"sort\":1,\"subItemTypeAttrId\":\"100041\",\"type\":\"expandAttr\"},{\"content\":\"11\",\"createTime\":1662083370000,\"createTimeString\":\"2022-09-02 09:49:30\",\"creater\":\"10001\",\"id\":\"202209020949280005788\",\"itemId\":\"202209020949150001521\",\"name\":\"教材依據(jù)\",\"searchFlag\":\"1\",\"sort\":2,\"subItemTypeAttrId\":\"100042\",\"type\":\"expandAttr\"},{\"content\":\"11\",\"createTime\":1662083371000,\"createTimeString\":\"2022-09-02 09:49:31\",\"creater\":\"10001\",\"id\":\"202209020949290005789\",\"itemId\":\"202209020949150001521\",\"name\":\"關(guān)鍵字\",\"searchFlag\":\"1\",\"sort\":3,\"subItemTypeAttrId\":\"100043\",\"type\":\"expandAttr\"}],\"auditCount\":0,\"auditStatus\":0,\"childItemList\":[],\"createTime\":1662083350000,\"createTimeString\":\"2022-09-02 09:49:10\",\"creater\":\"10001\",\"delFlag\":\"0\",\"difficult\":\"3\",\"id\":\"202209020949150001521\",\"isComposite\":0,\"isTopVersion\":0,\"itemCode\":\"KJCJ202209020949140001501\",\"itemContent\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">2.<span style=\\\"color: #333333; font-family: Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 14px; text-align: justify; background-color: #FFFFFF;\\\">按照并購雙方行業(yè)相關(guān)性劃分,判斷并購類型(橫向并購or混合并購)</span></p>\",\"itemKnowledgeList\":[{\"id\":\"202209020949300001537\",\"itemId\":\"202209020949150001521\",\"knowledgeId\":\"1240004\",\"knowledgeStr\":\"2020年經(jīng)濟(jì)法基礎(chǔ)/第一章總論/第一節(jié)法律基礎(chǔ)/一、法和法律/(一)法和法律的概念\",\"level\":\"1\",\"pid\":\"202209020946580001519\"}],\"itemLevel\":1,\"itemSource\":\"202208301413310000412\",\"itemTypeId\":\"4\",\"itemVersion\":\"1\",\"keyWord\":\"\",\"knowledgeId\":\"1240004\",\"knowledgeStr\":\"2020年經(jīng)濟(jì)法基礎(chǔ)/第一章總論/第一節(jié)法律基礎(chǔ)/一、法和法律/(一)法和法律的概念\",\"knowledgeSyllabusName\":\"2020年經(jīng)濟(jì)法基礎(chǔ)\",\"lockStatus\":1,\"modifyChlidItems\":[],\"paperCount\":0,\"paperItemRelation\":{},\"paperStructure\":{},\"parentId\":\"202209020946580001519\",\"processedItemContent\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">2.<span style=\\\"color: #333333; font-family: Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 14px; text-align: justify; background-color: #FFFFFF;\\\">按照并購雙方行業(yè)相關(guān)性劃分,判斷并購類型(橫向并購or混合并購)</span></p>\",\"score\":2,\"sort\":2,\"sourceType\":\"2\",\"structId\":\"\",\"subItemTypeId\":\"20180228155501000004\",\"subjectId\":\"4\",\"updateTime\":1662083350000,\"updateTimeString\":\"2022-09-02 09:49:10\",\"updater\":\"10001\"}";
        String newStr = "{\"abilityLevel\":\"2020101240000000000002\",\"activityId\":\"202208301413310000412\",\"addLibTime\":1662083360000,\"analysis\":\"\",\"ansKnowModelIds\":\"1#201812051814150000475\",\"answer\":\"AB\",\"ascriptionItemLib\":\"0\",\"attributeList\":[{\"content\":\"<p>A</p>\",\"id\":\"202209021135210005855\",\"itemId\":\"202209020949150001521\",\"knowModelRelId\":\"201812051814150000475\",\"name\":\"A\",\"sort\":1,\"type\":\"option\"},{\"content\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">B</p>\",\"id\":\"202209021135210005856\",\"itemId\":\"202209020949150001521\",\"name\":\"B\",\"sort\":2,\"type\":\"option\"},{\"content\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">C</p>\",\"id\":\"202209021135210005857\",\"itemId\":\"202209020949150001521\",\"name\":\"C\",\"sort\":3,\"type\":\"option\"},{\"content\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">D</p>\",\"id\":\"202209021135210005858\",\"itemId\":\"202209020949150001521\",\"name\":\"D\",\"sort\":4,\"type\":\"option\"},{\"content\":\"11\",\"createTime\":1662089721000,\"createTimeString\":\"2022-09-02 11:35:21\",\"creater\":\"10001\",\"id\":\"202209021135210005859\",\"itemId\":\"202209020949150001521\",\"name\":\"大綱依據(jù)\",\"searchFlag\":\"1\",\"sort\":1,\"subItemTypeAttrId\":\"100041\",\"type\":\"expandAttr\"},{\"content\":\"11\",\"createTime\":1662089721000,\"createTimeString\":\"2022-09-02 11:35:21\",\"creater\":\"10001\",\"id\":\"202209021135210005860\",\"itemId\":\"202209020949150001521\",\"name\":\"教材依據(jù)\",\"searchFlag\":\"1\",\"sort\":2,\"subItemTypeAttrId\":\"100042\",\"type\":\"expandAttr\"},{\"content\":\"11\",\"createTime\":1662089722000,\"createTimeString\":\"2022-09-02 11:35:22\",\"creater\":\"10001\",\"id\":\"202209021135210005861\",\"itemId\":\"202209020949150001521\",\"name\":\"關(guān)鍵字\",\"searchFlag\":\"1\",\"sort\":3,\"subItemTypeAttrId\":\"100043\",\"type\":\"expandAttr\"}],\"auditCount\":0,\"auditStatus\":0,\"childItemList\":[],\"createTime\":1662083350000,\"createTimeString\":\"2022-09-02 09:49:10\",\"creater\":\"10001\",\"delFlag\":\"0\",\"difficult\":\"5\",\"id\":\"202209020949150001521\",\"isComposite\":0,\"isTopVersion\":0,\"itemCode\":\"KJCJ202209020949140001501\",\"itemContent\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">2.<span style=\\\"color: #333333; font-family: Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 14px; text-align: justify; background-color: #FFFFFF;\\\">按照并購雙方行業(yè)相關(guān)性劃分,判斷并購類型(橫向并購or混合并購)</span></p>\",\"itemKnowledgeList\":[{\"id\":\"202209021135230001557\",\"itemId\":\"202209020949150001521\",\"knowledgeId\":\"1240004\",\"knowledgeStr\":\"2020年經(jīng)濟(jì)法基礎(chǔ)/第一章總論/第一節(jié)法律基礎(chǔ)/一、法和法律/(一)法和法律的概念\",\"level\":\"1\",\"pid\":\"202209020946580001519\"}],\"itemLevel\":1,\"itemSource\":\"202208301413310000412\",\"itemTypeId\":\"4\",\"itemVersion\":\"2\",\"keyWord\":\"\",\"knowledgeId\":\"1240004\",\"knowledgeStr\":\"2020年經(jīng)濟(jì)法基礎(chǔ)/第一章總論/第一節(jié)法律基礎(chǔ)/一、法和法律/(一)法和法律的概念\",\"knowledgeSyllabusName\":\"2020年經(jīng)濟(jì)法基礎(chǔ)\",\"lockStatus\":1,\"modifyChlidItems\":[],\"paperCount\":0,\"paperItemRelation\":{},\"paperStructure\":{},\"parentId\":\"202209020946580001519\",\"processedItemContent\":\"<p style=\\\"font-family:&#39;Times New Roman&#39;,&#39;宋體&#39;;font-size:12pt;padding:0;margin:0;\\\">2.<span style=\\\"color: #333333; font-family: Arial, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei&quot;, &quot;WenQuanYi Micro Hei&quot;, sans-serif; font-size: 14px; text-align: justify; background-color: #FFFFFF;\\\">按照并購雙方行業(yè)相關(guān)性劃分,判斷并購類型(橫向并購or混合并購)</span></p>\",\"score\":2,\"sort\":2,\"sourceType\":\"2\",\"structId\":\"\",\"subItemTypeId\":\"20180228155501000004\",\"subjectId\":\"4\",\"updateTime\":1662089720000,\"updateTimeString\":\"2022-09-02 11:35:20\",\"updater\":\"10001\"}";
        System.out.println(new JsonCompareUtils().compare2Json(oldStr, newStr));
        System.out.println("\n========測試復(fù)雜json的比對============");
    }
}

JsonAndMapSortUtils 用于jsonArray排序

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import sun.misc.ASCIICaseInsensitiveComparator;
import java.util.*;
public class JsonAndMapSortUtils {
    /**
     * map排序
     * @param map
     * @param keySort
     * @param <k>
     * @param <v>
     * @return
     */
    public static <k,v> List mapByKeyToSort(Map<k,v> map , final Comparator keySort){
        List<Map.Entry<k,v>> entryList = new ArrayList<>(map.entrySet());
        Collections.sort(entryList, (o1, o2) -> keySort.compare(o1.getKey(),o2.getKey()));
        System.out.println("排序=====");
        entryList.forEach(m->{
            System.out.println(m.getKey()+"===>"+m.getValue());
        });
        return entryList;
    }
    /**
     * JSONArray排序
     * @param jsonArray
     * @param fildName
     * @param isAsc
     * @return
     */
    public static JSONArray jsonArrayToSort(JSONArray jsonArray,final String fildName,final boolean isAsc){
        JSONArray afterSortJsonArray = new JSONArray();
        List<JSONObject> objectList = new ArrayList<>();
        jsonArray.forEach(obj ->{
            objectList.add((JSONObject)obj);
        });
        Collections.sort(objectList, (o1, o2) -> {
            String fildValueA = o1.getString(fildName);
            String fildValueB = o2.getString(fildName);
            if (isAsc){
                return fildValueA.compareTo(fildValueB);
            }
            return fildValueB.compareTo(fildValueA);
        });
        objectList.forEach(obj->{
            afterSortJsonArray.add(obj);
        });
        return afterSortJsonArray;
    }
    /**
     *準(zhǔn)備map測試數(shù)據(jù)
     */
    public static Map<String,String> getMapData(){
        LinkedHashMap<String,String> map = new LinkedHashMap<>();
        map.put("key1","測試1");
        map.put("key3","測試3");
        map.put("key5","測試5");
        map.put("key2","測試2");
        map.put("key4","測試4");
        return map;
    }
    /**
     *準(zhǔn)備json測試數(shù)據(jù)
     */
    public static JSONArray getJsonArrayData(){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("userId","1001");
        jsonObject1.put("name","測試1");
        jsonArray.add(jsonObject1);
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("userId","1003");
        jsonObject3.put("name","測試3");
        jsonArray.add(jsonObject3);
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("userId","1002");
        jsonObject2.put("name","測試2");
        jsonArray.add(jsonObject2);
        return jsonArray;
    }
    public static void main(String[] args) {
        Map<String,String> map = JsonAndMapSortUtils.getMapData();
        JSONArray jsonArray = JsonAndMapSortUtils.getJsonArrayData();
        List afterSortMap = JsonAndMapSortUtils.mapByKeyToSort(map,new ASCIICaseInsensitiveComparator());
        JSONArray afterSortJsonArray_isAsc = JsonAndMapSortUtils.jsonArrayToSort(jsonArray,"userId",true);
        JSONArray afterSortJsonArray_noAsc = JsonAndMapSortUtils.jsonArrayToSort(jsonArray,"userId",false);
        System.out.println("map排序前:"+map);
        System.out.println("map排序后:"+afterSortMap+"\n");
        System.out.println("JsonArray排序前:"+jsonArray);
        System.out.println("JsonArray排序后==》升序:"+afterSortJsonArray_isAsc);
        System.out.println("JsonArray排序后==》降序:"+afterSortJsonArray_noAsc);
    }
}

源碼走讀

整個(gè)源碼調(diào)用鏈路如下圖,簡單來說過程就是:object拆分解析-新舊數(shù)據(jù)逐個(gè)對比-結(jié)果信息組裝三個(gè)步驟

到此這篇關(guān)于Json字符串內(nèi)容比較-超實(shí)用版的文章就介紹到這了,更多相關(guān)Json字符串內(nèi)容比較內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 一篇文章帶你入門Java字面量和常量

    一篇文章帶你入門Java字面量和常量

    這篇文章主要介紹了探究Java的常量,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-08-08
  • idea2020.2卡死在reading maven projects

    idea2020.2卡死在reading maven projects

    這篇文章主要介紹了idea2020.2卡死在reading maven projects,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • Java的延遲隊(duì)列之DelayQueue解讀

    Java的延遲隊(duì)列之DelayQueue解讀

    這篇文章主要介紹了Java的延遲隊(duì)列之DelayQueue解讀,DelayQueue的底層存儲(chǔ)是一個(gè)PriorityQueue,PriorityQueue是一個(gè)可排序的Queue,其中的元素必須實(shí)現(xiàn)Comparable接口的compareTo方法,需要的朋友可以參考下
    2023-12-12
  • Spring Boot集成Java DSL的實(shí)現(xiàn)代碼

    Spring Boot集成Java DSL的實(shí)現(xiàn)代碼

    這篇文章主要介紹了Spring Boot集成Java DSL的實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-01-01
  • Java IO流之原理分類與節(jié)點(diǎn)流文件操作詳解

    Java IO流之原理分類與節(jié)點(diǎn)流文件操作詳解

    流(Stream)是指一連串的數(shù)據(jù)(字符或字節(jié)),是以先進(jìn)先出的方式發(fā)送信息的通道,數(shù)據(jù)源發(fā)送的數(shù)據(jù)經(jīng)過這個(gè)通道到達(dá)目的地,按流向區(qū)分為輸入流和輸出流
    2021-10-10
  • 詳解如何在低版本的Spring中快速實(shí)現(xiàn)類似自動(dòng)配置的功能

    詳解如何在低版本的Spring中快速實(shí)現(xiàn)類似自動(dòng)配置的功能

    這篇文章主要介紹了詳解如何在低版本的Spring中快速實(shí)現(xiàn)類似自動(dòng)配置的功能,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-05-05
  • Java 的雙重分發(fā)與 Visitor 模式實(shí)例詳解

    Java 的雙重分發(fā)與 Visitor 模式實(shí)例詳解

    這篇文章主要介紹了Java 的雙重分發(fā)與 Visitor 模式實(shí)例詳解,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-07-07
  • Kafka單機(jī)多broker實(shí)例集群搭建教程詳解

    Kafka單機(jī)多broker實(shí)例集群搭建教程詳解

    Apache?Kafka?是一個(gè)分布式流處理平臺,廣泛應(yīng)用于日志收集、監(jiān)控?cái)?shù)據(jù)聚合等,本文將詳細(xì)介紹如何在一個(gè)單機(jī)上搭建多個(gè)Kafka?Broker實(shí)例的步驟,希望對大家有所幫助
    2025-03-03
  • 解決java-jar報(bào)錯(cuò):xxx.jar 中沒有主清單屬性的方法

    解決java-jar報(bào)錯(cuò):xxx.jar 中沒有主清單屬性的方法

    在使用 java -jar xxx.jar 命令運(yùn)行 Java 應(yīng)用程序時(shí),遇到了以下錯(cuò)誤:xxx.jar 中沒有主清單屬性,這個(gè)錯(cuò)誤表示 JAR 文件缺少必要的啟動(dòng)信息,本文將介紹該錯(cuò)誤的原因以及如何通過修改 pom.xml 文件來解決,需要的朋友可以參考下
    2024-11-11
  • Java緩存池代碼實(shí)例詳解

    Java緩存池代碼實(shí)例詳解

    本篇文章主要介紹了Java實(shí)現(xiàn)簡單的緩存方法實(shí)例,需要的朋友可以參考下
    2017-04-04

最新評論