当前位置:   article > 正文

两个json对比差异,并输出差异结果

json对比差异
package com.cwq.demo02;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/** 
 * @author Carpoor  
 * @date 2021年5月19日 
 */
public class JsonUtil {
   
	
	public static Set<String> set = new HashSet<>();
	
	static {
   
		set.add("String");
		set.add("Integer");
		set.add("Double");
	}
	
	public static <T>T str2Obj(String json, Class<T> clazz) {
   
		Gson gson = new GsonBuilder()
				.disableHtmlEscaping()
				.serializeNulls()
				.create();
		return gson.fromJson(json, clazz);
	}
	
	public static String obj2Str(Object obj) {
   
		Gson gson = new GsonBuilder()
				.disableHtmlEscaping()
				.serializeNulls()
				.create();
		return gson.toJson(obj);
	}
	
	public static Map jsonCompare(String currentJson, String expectJson) {
   
		Map<String, String> result = new HashMap<>();
		Map<String, Object> curr = str2Obj(currentJson, Map.class);
		Map<String, Object> exp = str2Obj(expectJson, Map.class);
		
		mapProc(curr, exp, result, "");
		
		return result;
	}
	
	public static void mapProc(Map<String, Object> curr, Map<String, Object> exp, Map<String, String> result, String keyStr) {
   
		
		if (curr.size() != exp.size()) {
   
			result.put(keyStr == "" ? "首层":keyStr, String.format("key=[%s]Map字段个数不一致,期望为[%s],但当前为[%s]", keyStr == "" ? "首层":keyStr, exp.size(), curr.size()));
		}
		
		for (String currKey : curr.keySet()) {
   
			String keyStrCopy = keyStr + "."+ currKey;
			if (keyStrCopy.indexOf(".") == 0) {
   
				keyStrCopy = keyStrCopy.substring(1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/1014750
推荐阅读
相关标签
  

闽ICP备14008679号