JSON字符串先转对象,在比较对象字段对应的内容。 补充一下,可用String.valueOf()替换toString()方法,可防止空值报错。 话不多说,直接上代码:
str1 = {\"id\":\"177\",\"name\":\"张三\",\"age\":\"21\",\"联系方式\":\"13355556666\",\"createtime\":\"2022-01-21 16:49:42\"};
str2 = {\"id\":\"177\",\"name\":\"李四\",\"age\":\"23\",\"联系方式\":\"13355556666\",\"createtime\":\"2022-01-24 16:49:42\"};
Map<String,String> map =new HashMap<String,String>();
JSONObject obj1 = new JSONObject().fromObject(str1);
JSONObject obj2 = new JSONObject().fromObject(str2);
Iterator<String> i = obj1.keys();
while (i.hasNext()) {
String key = i.next();
Object obj11 = obj1.get(key);
Object obj22 = obj2.get(key);
if(!obj11.equals(obj22)){
String value = "字段:" + key+ " 修改前:" +obj1.get(key).toString() + " 修改后:" +obj2.get(key).toString()+" ";
map.put(key, value);
System.out.println(value);
}
}
|