我想要获取使用Newtonsoft进行比较时不匹配的JSON部分的列表。
我有下面的代码来比较:
JObject xpctJSON = JObject.Parse(expectedJSON);
JObject actJSON = JObject.Parse(actualJSON);
bool res = JToken.DeepEquals(xpctJSON, actJSON);
但是找不到任何返回diff的内容。
发布于 2017-11-14 20:08:42
只是为了方便以后的查询。我遇到了一个很好的json diff工具。对于json结构的diff/patch,它可以完美地工作:
jsondiffpatch.net还提供了一个nuget包。
用法很简单。
var jdp = new JsonDiffPatch();
JToken diffResult = jdp.Diff(leftJson, rightJson);
发布于 2018-12-06 23:33:50
我的解决方案是基于前面答案中的想法:
public static JObject FindDiff(this JToken Current, JToken Model)
{
var diff = new JObject();
if (JToken.DeepEquals(Current, Model)) return diff;
switch(Current.Type)
{
case JTokenType.Object:
{
var current = Current as JObject;
var model = Model as JObject;
var addedKeys = current.Properties().Select(c => c.Name).Except(model.Properties().Select(c => c.Name));
var removedKeys = model.Properties().Select(c => c.Name).Except(current.Properties().Select(c => c.Name));
var unchangedKeys = current.Properties().Where(c => JToken.DeepEquals(c.Value, Model[c.Name])).Select(c => c.Name);
foreach (var k in addedKeys)
{
diff[k] = new JObject
{
["+"] = Current[k]
};
}
foreach (var k in removedKeys)
{
diff[k] = new JObject
{
["-"] = Model[k]
};
}
var potentiallyModifiedKeys = current.Properties().Select(c => c.Name).Except(addedKeys).Except(unchangedKeys);
foreach (var k in potentiallyModifiedKeys)
{
var foundDiff = FindDiff(current[k], model[k]);
if(foundDiff.HasValues) diff[k] = foundDiff;
}
}
break;
case JTokenType.Array:
{
var current = Current as JArray;
var model = Model as JArray;
var plus = new JArray(current.Except(model, new JTokenEqualityComparer()));
var minus = new JArray(model.Except(current, new JTokenEqualityComparer()));
if (plus.HasValues) diff["+"] = plus;
if (minus.HasValues) diff["-"] = minus;
}
break;
default:
diff["+"] = Current;
diff["-"] = Model;
break;
}
return diff;
}
发布于 2015-08-11 02:14:38
这是一个相对古老的问题,但发布了一种可能的方法来解决这个问题,假设您想要的结果正是哪些属性值被更改
string sourceJsonString = "{'name':'John Doe','age':'25','hitcount':34}";
string targetJsonString = "{'name':'John Doe','age':'26','hitcount':30}";
JObject sourceJObject = JsonConvert.DeserializeObject<JObject>(sourceJsonString);
JObject targetJObject = JsonConvert.DeserializeObject<JObject>(targetJsonString);
if (!JToken.DeepEquals(sourceJObject, targetJObject))
{
foreach (KeyValuePair<string, JToken> sourceProperty in sourceJObject)
{
JProperty targetProp = targetJObject.Property(sourceProperty.Key);
if (!JToken.DeepEquals(sourceProperty.Value, targetProp.Value))
{
Console.WriteLine(string.Format("{0} property value is changed", sourceProperty.Key));
}
else
{
Console.WriteLine(string.Format("{0} property value didn't change", sourceProperty.Key));
}
}
}
else
{
Console.WriteLine("Objects are same");
}
注意:这还没有针对非常深的层次结构进行测试。
https://stackoverflow.com/questions/24876082
复制相似问题