對Json文件進行去重合併成一個新的Json文件

目的:假如json文件A和json文件B,或者json字符串A和json字符串B,要求主體按B來,B中沒有的按A來,有相沖突的按B來,然後生成一個新的json文件或json字符串。
主要用到的技術是 JsonIterator 和JSONObject,網上可以搜maven依賴。這裏記錄下來,效率有點低,有可以改進的地方請留言。

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;

import java.io.*;
import java.util.*;

public class OutPut {

   public static void main(String[] args) throws IOException {
        String json = "null";
        String json1 = "null";
        try {
            long begin1 = System.currentTimeMillis();
            json = readJsonData("C:\\Users\\51171\\Desktop\\json\\deviceConfig.json");
            json1 = readJsonData("C:\\Users\\51171\\Desktop\\json\\模板配置.json");
            long end1 = System.currentTimeMillis();
            System.out.println("把json文件解析成json字符串,用時: " + (end1-begin1) + "毫秒");
        } catch (IOException e) {
            e.printStackTrace();
        }
        merge(json, json1);
    }
    public static String merge(String json, String json1) throws IOException {
        Map<String, String> find = new HashMap<>();
        String result = merge(json, json1, find);
        return result;
    }

    public static String merge(String json, String json1, Map<String, String> find) throws IOException {
        long begin2 = System.currentTimeMillis();
        check(json, find);
        check(json1, find);

        long end = System.currentTimeMillis();
        System.out.println("把json字符串轉換成map: " + (end-begin2) + "毫秒");

        String result = generateJson(find);
        System.out.println(result);
        long end2 = System.currentTimeMillis();
        System.out.println("把map轉換成新的json字符串: " + (end2-begin2) + "毫秒");
//        write(result);
//        long end3 = System.currentTimeMillis();
//        System.out.println("對json字符串去重合並之後,轉換成json文件用時: " + (end3-begin2) + "毫秒");
        return result;
    }

    //將map轉換成新的json字符串。
    public static String generateJson(Map<String, String> map) {
        JSONObject object = new JSONObject();
        //object類型
        Map<String, JSONObject> helObj = new HashMap<>();
        //array類型
        Map<String, JSONArray> helArr = new HashMap<>();
        //同一個array下的每段object共用同一個array
        Map<String, JSONArray> helArr2 = new HashMap<>();
        //同一個array下每段object下的字段共用同一個object
        Map<String, JSONObject> help = new HashMap<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {

            String[] arr = entry.getKey().split("\\.");
            for (int i = 1; i < arr.length; i++) {
                if (arr[i].endsWith("]") && !helArr.containsKey(arr[i])) {
                    JSONArray object1 = new JSONArray();
                    JSONObject js = new JSONObject();
                    if (helArr2.containsKey(arr[i].substring(0, arr[i].length()-3))) {
                        helArr.put(arr[i], helArr2.get(arr[i].substring(0, arr[i].length()-3)));
                        helArr2.get(arr[i].substring(0, arr[i].length()-3)).add(js);
                        help.put(arr[i], js);
                        continue;
                    }
                    object1.add(js);
                    help.put(arr[i], js);
                    helArr.put(arr[i], object1);
                    helArr2.put(arr[i].substring(0, arr[i].length()-3), object1);
                    if (i == 1) {
                        object.put(arr[i].substring(0, arr[i].length()-3), object1);
                    } else if (i != arr.length-1) {
                        helObj.get(arr[i-1]).put(arr[i].substring(0, arr[i].length()-3), object1);
                    }
                } else if (!arr[i].endsWith("]") && !helObj.containsKey(arr[i])) {
                    JSONObject object1 = new JSONObject();
                    helObj.put(arr[i], object1);
                    if (i == 1) {
                        object.put(arr[i], object1);
                    } else if (i != arr.length-1) {
                        if (arr[i-1].endsWith("]")) {
                            help.get(arr[i-1]).put(arr[i], checkValue(entry.getValue()));
                        } else {
                            helObj.get(arr[i-1]).put(arr[i], object1);
                        }
                    } else {
                        if (arr[i-1].endsWith("]")) {
                            help.get(arr[i-1]).put(arr[i], checkValue(entry.getValue()));
                        }else {
                            helObj.get(arr[i-1]).put(arr[i], checkValue(entry.getValue()));
                        }
                    }
                } else if (!arr[i].endsWith("]") && helObj.containsKey(arr[i])) {
                    if (i == arr.length-1) {
                        if (arr[i-1].endsWith("]")) {
                            help.get(arr[i-1]).put(arr[i], checkValue(entry.getValue()));
                        } else {
                            helObj.get(arr[i-1]).put(arr[i], checkValue(entry.getValue()));
                        }
                    }
                }
            }
        }
        //讓值爲null的還按 null輸出。
        return JSONObject.toJSONString(object, SerializerFeature.WriteMapNullValue);
    }

    //因存的時候都是按string,好處理,轉換成新的json字符串時要轉換值的格式。
    public static Object checkValue(String str) {
        Object obj;
        if (str.equals("true") || str.equals("false")) {
            obj = Boolean.valueOf(str);
            return obj;
        }
        if ("null".equals(str)) {
            return null;
        }
        try {
            obj = Integer.valueOf(str.trim());
        } catch (Exception e) {
            obj = str;
        }
        return obj;
    }

    //將json字符串拆開存進map,鍵的格式爲“$.class.name”,如果是數組則“$.class[0].name”
    public static void check(String json, Map<String, String> find) {
        Any value = JsonIterator.deserialize(json);
        String str = "$";
        Map<String, Any> map = value.asMap();
        for (Map.Entry<String, Any> entry : map.entrySet()) {
            String cur = str;
            cur += "." + entry.getKey();
            value = entry.getValue();
            if (value.toString().trim().charAt(0) == '[') {
                 checkList(value, cur, find);
            } else if (!value.toString().contains(":")) {
                if (!find.containsKey(cur)){
                    find.put(cur, value.toString());
                }
            } else {
                checkMap(value, cur, find);
            }
        }
    }

    //將json字符串裏的“鍵值”存進map。
    public static void checkMap(Any any, String str, Map<String, String> find) {
        Map<String, Any> map = any.asMap();
        for (Map.Entry<String, Any> entry : map.entrySet()) {
            String cur = str;
            cur += "." + entry.getKey();
            any = entry.getValue();
            if (any.toString().trim().charAt(0) == '[') {
                checkList(any, cur, find);
            } else if (!any.toString().contains(":")) {
                if (!find.containsKey(cur)) {
                    find.put(cur, any.toString());
                }
            } else {
                checkMap(any, cur, find);
            }
        }
    }

     //將json字符串裏的array存進map。
    public static void checkList(Any val, String cur, Map<String, String> find) {
        List<Any> list = val.asList();
        for (int i=0; i<list.size(); i++) {
            for (Map.Entry<String, Any> entry1 : list.get(i).asMap().entrySet()) {
                String cur1 = cur + "["+ i +"]";
                cur1 += "." + entry1.getKey();
                if (!find.containsKey(cur1)){
                    find.put(cur1, entry1.getValue().toString());
                }
            }
        }
    }

    public static String readJsonData(String pactFile) throws IOException {
        // 讀取文件數據
        StringBuffer strbuffer = new StringBuffer();
        File myFile = new File(pactFile);
        if (!myFile.exists()) {
            System.err.println("Can't Find " + pactFile);
        }
        try {
            FileInputStream fis = new FileInputStream(pactFile);
            InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
            BufferedReader in  = new BufferedReader(inputStreamReader);

            String str;
            while ((str = in.readLine()) != null) {
                strbuffer.append(str.trim());
            }
            in.close();
        } catch (IOException e) {
            e.getStackTrace();
        }
        String str =  strbuffer.toString();
        return str;
    }

    //寫出文件,我後面沒用到了,我只轉換成新的json字符串。
        public static void write(String str) throws IOException {
        File file = new File("C:\\Users\\51171\\Desktop\\json\\c.json");
        if(!file.exists()){
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fw);
        out.write(str);
        out.close();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章