Java实现 json diff 工具

发布时间:2024年01月09日

文章目录


依赖

<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"
    }
]
文章来源:https://blog.csdn.net/qq_40213825/article/details/135369379
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。