package com.sinoeyes.pilotrun; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.ObjectUtils; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class ComplateJson { /** * * @Title: compare * @Description: TODO(这里用一句话描述这个方法的作用) * @param @param obj1 * @param @param obj2 * @param @param diffs 设定文件 * @return void 返回类型 * @throws */ @SuppressWarnings("rawtypes") public static void compare(JSONObject obj1, JSONObject obj2, List<String> diffs) { String message = "字符串差异:字段【%s】,值【%s】!=【%s】"; String lostField = "缺失字段:【%s】"; String lostJson = "json对象差异:【%s】"; Iterator iter1 = obj1.keys(); while (iter1.hasNext()) { Object key = iter1.next(); if (obj2.containsKey(key)) { Object value = obj2.get(key); if (value instanceof String) { boolean ret = ObjectUtils.notEqual(obj1.get(key), obj2.get(key)); if (ret) { diffs.add(String.format(message, key, obj1.get(key), obj2.get(key))); } } else if (value instanceof JSONArray) { JSONArray array1 = (JSONArray) obj1.get(key); JSONArray array2 = (JSONArray) obj2.get(key); for (int i = 0; i < array1.size(); i++) { JSONObject o1 = (JSONObject) array1.get(i); // 遍历obj2 boolean result = false; for (int j = 0; j < array2.size(); j++) { JSONObject o2 = (JSONObject) array2.get(j); ArrayList<String> subDiff = new ArrayList<>(); compare(o1, o2, subDiff); if (subDiff.isEmpty()) { result = true; break; } } if (!result) { diffs.add(String.format(lostJson, o1.toString())); } } } else if (value instanceof JSONObject) { JSONObject o1 = (JSONObject) obj1.get(key); JSONObject o2 = (JSONObject) obj2.get(key); compare(o1, o2, diffs); } } else { diffs.add(String.format(lostField, key)); } } } public static void main(String[] args) { try { // String path1 = "D:\\99_TEMP\\sample1.json"; // String path2 = "D:\\99_TEMP\\sample2.json"; // String path1 = "D:\\99_TEMP\\sample1 - 副本.json"; // String path2 = "D:\\99_TEMP\\sample2 - 副本.json"; String path1 = "D:\\99_TEMP\\left.json"; String path2 = "D:\\99_TEMP\\right.json"; File file1 = new File(path1); File file2 = new File(path2); String str1 = FileUtils.readFileToString(file1); String str2 = FileUtils.readFileToString(file2); JSONObject json1 = JSONObject.fromObject(str1); JSONObject json2 = JSONObject.fromObject(str2); List<String> list = new ArrayList<String>(); compare(json1, json2, list); for (String str : list) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } } }
json比较
猜你喜欢
转载自lambertsprite.iteye.com/blog/2296349
今日推荐
周排行