Detect differences between two json files in c#

前端 未结 3 1613
情歌与酒
情歌与酒 2021-01-04 06:28

For example, if I have the following json texts:

 object1{
     field1: value1;
     field2: value2;
     field3: value3;
 }

 object1{
     field1: value1;
         


        
3条回答
  •  萌比男神i
    2021-01-04 06:43

    I recommend you use Weakly-Typed JSON Serialization and write a routine that uses JsonObject like this:

    String JsonDifferenceReport(String objectName,
                                JsonObject first,
                                JsonObject second)
    {
      if(String.IsNullOrEmpty(objectName))
        throw new ArgumentNullException("objectName");
      if(null==first)
        throw new ArgumentNullException("first");
      if(null==second)
        throw new ArgumentNullException("second");
      List allKeys = new List();
      foreach(String key in first.Keys)
        if (!allKeys.Any(X => X.Equals(key))) allKeys.Add(key);
      foreach(String key in second.Keys)
        if (!allKeys.Any(X => X.Equals(key))) allKeys.Add(key);
      String results = String.Empty;
      foreach(String key in allKeys)
      {
        JsonValue v1 = first[key];
        JsonValue v1 = second[key];
        if (((null==v1) != (null==v2)) || !v1.Equals(v2))
        {
          if(String.IsNullOrEmpty(results))
          {
             results = "differences: {\n";
          }
          results += "\t" + objectName + ": {\n";
          results += "\t\tfield: " + key + ",\n";
          results += "\t\toldvalue: " + (null==v1)? "null" : v1.ToString() + ",\n";
          results += "\t\tnewvalue: " + (null==v2)? "null" : v2.ToString() + "\n";
          results += "\t}\n";
        }
      }
      if(!String.IsNullOrEmpty(results))
      {
        results += "}\n";
      }
      return results;
    }
    

    Your choice whether to get reports recursively inside JsonValue v1 and v2, instead of just using their string representation as I did here.

    If you wanted to go recursive, it might change the above like this:

      if ((null==v1) || (v1.JsonType == JsonType.JsonPrimitive)
       || (null==v2) || (v2.JsonType == JsonType.JsonPrimitive))
      {
        results += "\t\tfield: " + key + ",\n";
        results += "\t\toldvalue: " + (null==v1) ? "null" : v1.ToString() + ",\n";
        results += "\t\tnewvalue: " + (null==v2) ? "null" : v2.ToString() + "\n";
      }
      else
      {
        results + JsonDifferenceReport(key, v1, v2);
      }
    

    -Jesse

提交回复
热议问题