检测c#中两个json文件之间的差异

例如,如果我有以下json文本:

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

我需要在c#中读取文件并显示差异。 即它可以返回以下对象:

 differences { object1: { field: field2, old_value: value2, new_value: newvalue2} } 

是否有一些API或建议来做到这一点?

我建议你使用Weakly-Typed JSON Serialization并编写一个使用JsonObject的例程,如下所示:

 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; } 

您是否可以在JsonValue v1和v2中递归获取报告,而不是像我在这里一样使用它们的字符串表示。

如果你想要递归,可能会改变上面这样:

  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

出于某种原因,我无法在我的Web API项目中使用JsonObject。 我使用JSON.Net,下面是我获取差异的方法。 它将给出一系列差异。

 private static string GetJsonDiff(string action, string existing, string modified, string objectType) { // convert JSON to object JObject xptJson = JObject.Parse(modified); JObject actualJson = JObject.Parse(existing); // read properties var xptProps = xptJson.Properties().ToList(); var actProps = actualJson.Properties().ToList(); // find differing properties var auditLog = (from existingProp in actProps from modifiedProp in xptProps where modifiedProp.Path.Equals(existingProp.Path) where !modifiedProp.Value.Equals(existingProp.Value) select new AuditLog { Field = existingProp.Path, OldValue = existingProp.Value.ToString(), NewValue = modifiedProp.Value.ToString(), Action = action, ActionBy = GetUserName(), ActionDate = DateTime.UtcNow.ToLongDateString(), ObjectType = objectType }).ToList(); return JsonConvert.SerializeObject(auditLog); }