Java实现 json diff 工具

文章目录


依赖

<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"
    }
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值