JSON对象或JSON数组字符串比较,最实用的比较策略

本篇主要是为了实现JSON数组或者JSON对象比较差异,统计不同之处,并最终将不同之处以JSON字符串形式写入文本文件里。

1.1Maven依赖引入

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.32</version>
</dependency>

 <dependency>
	<groupId>net.sf.json-lib</groupId>
	<artifactId>json-lib</artifactId>
	<classifier>jdk15</classifier>
	<version>2.4</version>
</dependency>

1.2工具类JSON字符串比较差异

// 从文件读取数据
 public String ReadFileToString(String filename) {
        StringBuffer xml = new StringBuffer();
        try {
            File file = new File(filename);
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String s = null;
            while ((s = bufferedReader.readLine()) != null) {
                xml.append(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xml.toString();
    }
 // json转map
    public void convertJsonToMap(Object json, String root, Map<String, Object> resultMap) {
        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;
                if (value instanceof JSONObject || value instanceof JSONArray) {
                    convertJsonToMap(value, newRoot, resultMap);
                } else {
                    resultMap.put(newRoot, value);
                }
            }
        } else if (json instanceof JSONArray) {
            // 只要是jsonArray就去开对待
            JSONArray jsonArray = (JSONArray) json;
            for (int i = 0; i < jsonArray.size(); i++) {
                Object vaule = jsonArray.get(i);
                String newRoot = "".equals(root) ? "[" + i + "]" : root + ".[" + i + "]";
                if (vaule instanceof JSONObject || vaule instanceof JSONArray) {
                    convertJsonToMap(vaule, newRoot, resultMap);
                } else {
                    resultMap.put(newRoot, vaule);
                }
            }
        }
    }
//将字符串写入文本文件
public void writeIntoText(String jsonresult, String oldname) {
//        Calendar calendar = Calendar.getInstance();
//        long timefile = calendar.getTimeInMillis();
        String dirname = "E:\\file\\final\\";
        File dirfile = new File(dirname);
        if (!dirfile.exists()) {
            dirfile.mkdirs();
        }
        String newname = oldname.substring(0, oldname.lastIndexOf(".xml"));
        String filename = dirname + newname + ".json";
        File file = new File(filename);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            FileWriter fw = new FileWriter(file); 
            BufferedWriter writer = new BufferedWriter(fw);
//            writer.write("比对XML共发现" + count + "处差别\n");
            writer.write(jsonresult);
            writer.flush();
            writer.close();
            fw.close();
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
//从文件夹中循环读取,文件
  private void readDirect(String olddirname, String newdirname) throws IOException, DocumentException {
        File olddir = new File(olddirname);
        File newdir = new File(newdirname);
        String oldname = null;
        String newname = null;
        File[] oldfiles = null;
        File[] newfiles = null;
        if (olddir.isDirectory() && newdir.isDirectory()) {
            oldfiles = olddir.listFiles();
            newfiles = newdir.listFiles();
        }
        for (int i = 0; i < oldfiles.length; i++) {
            oldname = oldfiles[i].getName();
            for (int j = 0; j < newfiles.length; j++) {
                if (oldname.equals(newfiles[j].getName())) {
                    newname = newfiles[j].getName();
                    log.info("本次跑的文件名为:"+newname);
                    differenceMap = new LinkedHashMap<>();
                    count = 0;
                    JSONStringCompare fn = new JSONStringCompare();
                    fn.campareJsonObject(olddirname + newname, newdirname + newname, oldname);
                }
            }
        }
    }
  // 分别比对
    private void campareMapoldToNew(Map<String, Object> oldMap, Map<String, Object> newMap) {
       
        for (Iterator<Map.Entry<String, Object>> it = oldMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, Object> item = it.next();// 得到的是key的一个key value集合
            String key = item.getKey();
            Object oldValue = item.getValue();
            if (newMap.containsKey(key)) {
                Object newValue = newMap.get(key);
                if (newValue.equals(oldValue)) {
                
                    continue;
                } else {
               
                    if (differenceMap.get("old" + key) == null || differenceMap.get("new" + key) == null) {
                        count++;
                        //log.info("key:" + key + "对应value不同   oldValue:" + oldValue + "    newValue:" + newValue + " 累计比对不同 " + count + "  处");
                        differenceMap.put("old" + key, oldValue);
                        differenceMap.put("new" + key, newValue);
                    } else {
                     
                    }
                }
            } else {

                count++;
             
                differenceMap.put("old" + key, oldValue);
                differenceMap.put("new" + key, "不存在");
            }
        }
        }

    // 比对
    private void campareMap(Map<String, Object> oldMap, Map<String, Object> newMap) {
    
        for (Iterator<Map.Entry<String, Object>> it = newMap.entrySet().iterator(); it.hasNext();) {

            Map.Entry<String, Object> item = it.next();// 得到的是key的一个key value集合
            String key = item.getKey();
            Object newValue = item.getValue();// key-value
       
              if (oldMap.containsKey(key)) {
                    Object oldValue = oldMap.get(key);
                    if (oldValue.equals(newValue)) {
                    
                        continue;
                    } else {
                     
                        if (differenceMap.get("old" + key) == null || differenceMap.get("new" + key) == null) {
                            count++;                                    
                            differenceMap.put("old" + key, oldValue);
                            differenceMap.put("new" + key, newValue);
                        } else {
                          
                        }
                    }

                } else {
                    count++;
                    differenceMap.put("old" + key, "不存在");
                    differenceMap.put("new" + key, newValue);

                }
            }
        }

 

 // 比对数据JSON比对
    public void campareJsonObject(String oldefilename, String newFileName, String oldname)
            throws IOException, DocumentException {
        // 递归遍历json对象所有的key-value,将其封装成path:value格式进行比较
        String oldsreadXml = ReadFileToString(oldefilename);
        String newsreadXml = ReadFileToString(newFileName);
        JSONObject oldJson = null, newJson = null;
        oldJson = xml2Json(oldsreadXml);
        newJson = xml2Json(newsreadXml);
        
        JSONArray oldarr=readjsonObject(oldJson);
        JSONArray newarr=readjsonObject(newJson);
        Map<String, Object> map1 = new LinkedHashMap<>();
        Map<String, Object> map2 = new LinkedHashMap<>();
      
        convertJsonToMap(oldJson, "", map1);
        convertJsonToMap(newJson, "", map2);
 
        
        campareMapoldToNew(map1, map2);
        campareMap(map1, map2);
   
        compareJSONArr(newarr, oldarr);
      
        // 将最终的比较结果把不相同的转换为json对象返回
        differenceMapdi.put("count", "xml比对共发现"+count+"处差别");
        differenceMapdi.putAll(differenceMap);
        JSONObject jbJsonObject=new JSONObject(differenceMapdi);
        String jsonObject = JSON.toJSONString(jbJsonObject, SerializerFeature.PrettyFormat);
      
        writeIntoText(jsonObject, oldname);
        log.info("总共" + count + "处不同");
    }

 

JSONArray格外比较:

 //为了剔除字段,组建方法
     private JSONArray readjsonObject(JSONObject json) {
         JSONArray jsonObject=new JSONArray();
         JSONObject CashValueDesjson=new JSONObject();
         Object CashValueobj = null ; 
       //  log.info("CashValue的值:"+CashValueobj);
         if(json.containsKey("CashValueDes")&& StringUtils.isNotEmpty(json.getString("CashValueDes"))
                 && !StringUtils.equals(json.getString("CashValueDes"),("结点值为空")))
         {
           //  log.info("存在CashValueDes就进行分离");
             CashValueDesjson=json.getJSONObject("CashValueDes");
             CashValueobj= new JSONTokener(CashValueDesjson.getString("CashValue")).nextValue();
         }
         if(CashValueobj instanceof net.sf.json.JSONObject) {
//             log.info("JSONObject格式处理");
             JSONObject CashValuejson=CashValueDesjson.getJSONObject("CashValue");
//             log.info("CashValuejson:"+CashValuejson);
             Object CashValueInfoObj=  new JSONTokener(CashValuejson.getString("CashValueInfo")).nextValue();
             if( CashValueInfoObj instanceof net.sf.json.JSONObject) {
                 jsonObject.add(JSON.parseArray(CashValuejson.getJSONObject("CashValueInfo").toString()));
             }else if(CashValueInfoObj instanceof net.sf.json.JSONArray) {
                 JSONArray CashValueInfoArr=CashValuejson.getJSONArray("CashValueInfo");
                 jsonObject.add(CashValueInfoArr);
             }
             CashValuejson.remove("CashValueInfo");
         }
        
         if(!StringUtils.equals(json.getString("PicFileDes"),("结点值为空"))) {
           //  log.info("PicFileDes:"+json.getString("PicFileDes"));
             JSONObject PicFileDesobj=json.getJSONObject("PicFileDes");
             if(!StringUtils.equals(PicFileDesobj.getString("PicFile"),("结点值为空"))) {
                 //判断picFile是否是jsonobject还是jsonArray
                 Object PicFileObj=  new JSONTokener(PicFileDesobj.getString("PicFile")).nextValue();
               //  log.info("PicFileObj:"+PicFileObj);
                 if(PicFileObj instanceof net.sf.json.JSONArray) {
                     //得到PicFile的jsonArray
                        JSONArray PicFileArr=PicFileDesobj.getJSONArray("PicFile");
                        for (int i=0; i<PicFileArr.size() ;i++) {
                            JSONObject PicFile_picinfo=PicFileArr.getJSONObject(i);
                           // log.info("PicFile_picinfo:"+PicFile_picinfo);
                            Object PicInfoObj=  new JSONTokener(PicFile_picinfo.getString("PicInfo")).nextValue();
                           // log.info("PicInfoObj:"+PicInfoObj);
                            if(PicInfoObj instanceof net.sf.json.JSONArray) {
                                //jsonArray格式就进行修改
                                JSONArray  PicInfoArray=PicFile_picinfo.getJSONArray("PicInfo");
                                jsonObject.add(PicInfoArray);
                                PicFile_picinfo.remove("PicInfo");
                            }
                        }
                       
                 }else {
                     JSONArray PicInfoarr=json.getJSONObject("PicFileDes").getJSONObject("PicFile").getJSONArray("PicInfo");
                     jsonObject.add(PicInfoarr);
                     json.getJSONObject("PicFileDes").getJSONObject("PicFile").remove("PicInfo");
                 }
             }
         }
       //  log.info("jsonObject:"+jsonObject);
         return jsonObject;
     }

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
可以把Java数组换成JSON数组字符串,也可以把JSON数组字符串换成Java数组,但是JSON数组字符串不能直接换成JSON数组对象,需要使用JSON库进行解析。 在Java中,可以使用Gson、Jackson等库将Java数组换成JSON数组字符串,示例如下: ```java import com.google.gson.Gson; public class Main { public static void main(String[] args) { String[] arr = {"hello", "world"}; Gson gson = new Gson(); String jsonArrayString = gson.toJson(arr); System.out.println(jsonArrayString); // ["hello","world"] } } ``` 同样的,也可以将JSON数组字符串换成Java数组,示例如下: ```java import com.google.gson.Gson; public class Main { public static void main(String[] args) { String jsonArrayString = "[\"hello\",\"world\"]"; Gson gson = new Gson(); String[] arr = gson.fromJson(jsonArrayString, String[].class); System.out.println(arr[0]); // hello System.out.println(arr[1]); // world } } ``` 但是,如果要将JSON数组字符串换成JSON数组对象,则需要使用JSON库进行解析,示例如下: ```java import org.json.JSONArray; public class Main { public static void main(String[] args) { String jsonArrayString = "[\"hello\",\"world\"]"; JSONArray jsonArray = new JSONArray(jsonArrayString); System.out.println(jsonArray.getString(0)); // hello System.out.println(jsonArray.getString(1)); // world } } ``` 在这个示例中,我们使用了`org.json.JSONArray`类来解析JSON数组字符串,并将其换成JSON数组对象。需要注意的是,这里的JSON数组对象不是Java中的数组对象,而是JSON库中的一种数据类型。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员路同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值