没有的话就引入依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.1</version>
</dependency>
这种方式忽略顺序 ,顺序不一样 ,内容一样,也会返回true
/**
* 比较两个json串是否相同
* @param currJson 当前json
* @param oldJson 旧的json
* @return true 表示一样,false表示不一样,默认返回 false
*/
public static boolean checkJsonModify(String currJson, String oldJson) {
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode1 = objectMapper.readTree(currJson);
JsonNode jsonNode2 = objectMapper.readTree(oldJson);
boolean equals = jsonNode1.equals(jsonNode2);
return equals;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return false;
}
自定义比较器
JsonComparator.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NumericNode;
import com.fasterxml.jackson.databind.node.TextNode;
import java.util.Comparator;
public class JsonComparator implements Comparator<JsonNode> {
@Override
public int compare(JsonNode o1, JsonNode o2) {
if (o1.equals(o2)) {
return 0;
}
if ((o1 instanceof TextNode) && (o2 instanceof TextNode)) {
//字符串类型
String s1 = o1.asText();
String s2 = o2.asText();
//忽略大小写
if (s1.equalsIgnoreCase(s2)) {
return 0;
}
}
if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)){
//数字类型
Double d1 = o1.asDouble();
Double d2 = o2.asDouble();
if (d1.compareTo(d2) == 0) {
return 0;
}
}
return 1;
}
}
使用方式
JsonComparator jsonComparator=new JsonComparator();
System.out.println(jsonNode1.equals(jsonComparator,jsonNode2));//true