我有两个json对象,并且将它们进行比较,但是会通过键和值进行比较, 我想仅通过键比较两个json对象, 我怎么办?
这是我的代码:
var jdp = new JsonDiffPatch();
var areEqual2 = jdp.Diff(json1, json2);
答案 0 :(得分:1)
您可以创建和使用这样的类:
class CustomComparer : IEqualityComparer<YourObjectType>
{
public bool Equals(YourObjectType first, YourObjectType second)
{
if (first == null | second == null) { return false; }
else if (first.Hash == second.Hash)
return true;
else return false;
}
public int GetHashCode(YourObjectType obj)
{
throw new NotImplementedException();
}
}
答案 1 :(得分:0)
您可以实现此目的的一种方法是,检索json中所有键的名称/路径并比较List。例如,
var path1 = GetAllPaths(json1).OrderBy(x=>x).ToList();
var path2 = GetAllPaths(json2).OrderBy(x=>x).ToList();
var result = path1.SequenceEqual(path2);
GetAllPaths定义为
private IEnumerable<string> GetAllPaths(string json)
{
var regex = new Regex(@"\[\d*\].",RegexOptions.Compiled);
return JObject.Parse(json).DescendantsAndSelf()
.OfType<JProperty>()
.Where(jp => jp.Value is JValue)
.Select(jp => regex.Replace(jp.Path,".")).Distinct();
}
答案 2 :(得分:0)
如果您想让2个json有所不同:
private List<string> GetDiff(List<string> path1, List<string> path2)
{
List<string> equal=new List<string>();
foreach (var j1 in path1)
{
foreach (var j2 in path2)
{
if (j1 == j2)
{
equal.Add(j1);
}
}
}
return equal;
}