分享

比较两个JSON不一样的地方,输出key

 huowufenghuang 2019-01-07
  • 摘要:我们在做开发的时候,通常需比较两个JSON不一样的地方,分析原因,找出错误。API只是比较是否一样,但不输出哪个Key不一样。所以自己写了一个工具。packagetool;importjava.io.ByteArrayOutputStream;importjava.io.InputStream;importjava.io.OutputStream;importjava.net.URL;importjava.util.Iterator;importnet.sf.json.JSO

  • 我们在做开发的时候,通常需比较两个JSON不一样的地方,分析原因,找出错误。API只是比较是否一样,但不输出哪个Key不一样。所以自己写了一个工具。
    package tool;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.URL;
    import java.util.Iterator;
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    import org.apache.commons.io.IOUtils;
    public class JsonDiff {
    public static void main(String[] args) {
    JSONObject json1 = JSONObject.fromObject("{"a":"a","b":"b","c":"c"}");
    JSONObject json2 = JSONObject.fromObject("{"a":"a1sfsfsf","b":"b","c":"c"}");
    compareJson(json1, json2,null);
    }
    public static void compareJson(JSONObject json1, JSONObject json2,String key) {
    Iterator i = json1.keys();
    while (i.hasNext()) {
    key = i.next();
    compareJson(json1.get(key), json2.get(key),key);
    }
    }
    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)) {
    System.out.println("key:"+key+",json1:"+ str1 +",json2:"+str2);
    }
    }
    public static void compareJson(JSONArray json1,JSONArray json2,String key) {
    Iterator i1= json1.iterator();
    Iterator i2= json2.iterator();
    while ( i1.hasNext()) {
    compareJson(i1.next(), i2.next(),key);
    }
    }
    public static JSONObject getJson(String url) {
    try {
    URL url1 = new URL(url);
    InputStream in = url1.openStream();
    OutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(in, out);
    String aa = out.toString();
    in.close();
    out.close();
    return JSONObject.fromObject(aa);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return new JSONObject();
    }
    }
  • 以上是比较两个JSON不一样的地方,输出key的内容,更多 输出 一样 两个 比较 地方 json key 的内容,请您使用右上方搜索功能获取相关信息。          

      本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
      转藏 分享 献花(0

      0条评论

      发表

      请遵守用户 评论公约

      类似文章 更多