<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-patch</artifactId>
<version>1.13</version>
</dependency>
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.fge.jsonpatch.diff.JsonDiff;
import com.idiudiu.common.model.UserModel;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class JsonDiffUtil {
public static String diff(Object object1, Object object2) {
String json1 = GsonUtil.dump2JsonString(object1);
String json2 = GsonUtil.dump2JsonString(object2);
return diff(json1, json2);
}
public static String diff(String json1, String json2) {
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode1 = objectMapper.readTree(json1);
JsonNode jsonNode2 = objectMapper.readTree(json2);
JsonNode jsonDiff = JsonDiff.asJson(jsonNode1, jsonNode2);
return objectMapper.writeValueAsString(jsonDiff);
} catch (Exception e) {
log.error("json diff error: ", e);
}
return null;
}
public static boolean jsonIsEqual(Object object1, Object object2) {
return "[]".equals(diff(object1, object2));
}
public static void main(String[] args) {
UserModel user1 = new UserModel();
user1.setName("san.zhang");
user1.setPassword("123456");
user1.setMobile("123344445556");
user1.setStatus(1);
UserModel user2 = new UserModel();
user2.setName("si.li");
user2.setPassword("123456");
user2.setAuthority(1);
System.out.println(diff(user1, user2));
}
}
import lombok.Data;
@Data
public class UserModel {
private Long id;
private String name;
private String password;
private Integer authority;
private Integer status;
private String operator;
private String mobile;
private String email;
}
运行结果:
[
{
"op": "remove",
"path": "/mobile"
},
{
"op": "move",
"path": "/authority",
"from": "/status"
},
{
"op": "replace",
"path": "/name",
"value": "si.li"
}
]