本篇主要是为了实现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;
}