java比较两段json不同工具类(两个同一类型的java对象比较也推荐转成JSON再进行比较)

本文介绍如何在Java中比较两个JSON对象的差异。通过将JSON对象转换为字符串进行比较,或者递归遍历JSON结构,针对不同类型的字段进行逐个比较。重点关注JSONObject和JSONArray的比较方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.Iterator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonDiff {
//  private static StringBuilder sb = new StringBuilder();

    @SuppressWarnings("unchecked")
    public static void compareJson(JSONObject json1, JSONObject json2,String key) {
        Iterator<String> i = json1.keys();
        while (i.hasNext()) {
            key =  i.next();
            compareJson(json1.get(key), json2.get(key),key);
        }
//        return sb.toString();
    }
    public static void compareJson(Object json1,Object json2,String key) {
        if (json1 instanceof JSONObject) {
            compareJson((JSONObject)json1,(JSONObject)json2,key);
        }else if (json1 instanceof JSONArray) {
            compareJson((JSONArray)json1,(JSONArray)json2,key);
        }else if(json1 instanceof String){
            compareJson((String)json1,(String)json2,key);
        }else {
            compareJson(json1.toString(),json2.toString(),key);
        }
    }
    public static void compareJson(String str1,String str2,String key) {
        if (!str1.equals(str2)) {
//          sb.append("key:"+key+ ",json1:"+ str1 +",json2:"+str2);
            System.out.println("key:"+key+ ",json1:"+ str1 +",json2:"+str2);
        }
    }
    public static void compareJson(JSONArray json1,JSONArray json2,String key) {
        if(json1 != null && json2 != null){
            Iterator i1= json1.iterator();
            Iterator i2= json2.iterator();
            while ( i1.hasNext()) {
                compareJson(i1.next(), i2.next(),key);
            }
        }
    }
}

JSON数映射在java中包括JSONObject,JSONArray,String。
比如下面这段json数据:

{
    "username""tom",
    "age":18,
    "address":[
                {"province":"上海市"},
                {"city":"上海市"},
                {"disrtict":"静安区"}
              ]
}

整体是一个JSONObject,字段username和age对应的值是String,字段address对应的是一个JSONArray。而JSONArray的内容又是一段又一段的JSONObject。所以整体代码思路先判断类型,直到类型是String时用字符串比较方法。其余的都需进行循环比较直到类型为String。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值