我建议您使用弱类型 JSON 序列化并编写一个使用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<String> allKeys = new List<String>();
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;
}
您可以选择是否在 v1 和 v2 中以递归方式获取报告JsonValue
,而不是像我在这里所做的那样仅使用它们的字符串表示。
如果你想递归,它可能会像这样改变上面的内容:
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);
}
-杰西