ValeraT1982 / ObjectsComparer

C# Framework provides mechanism to compare complex objects, allows to override comparison rules for specific properties and types.
MIT License
354 stars 87 forks source link

Can't compare nested elements from json #28

Closed 4yck closed 3 years ago

4yck commented 3 years ago

Hi,

I use package 1.4.1 comparing two json files to find differencies ignoring some dynamic data fields (e.g Id)

Having the following json files, I want to ignore only Data.Id and Note fields

JSON_1: { "Data": [ { "Id": 7353, "Name": null, "Type": null, "Note": "Transfer test", "DocumentType": null } ], "Id": 356, "IsSuccess": true, "ErrorReason": "None", "ErrorCode": "None" }

JSON_2: { "Data": [ { "Id": 6563, "Name": null, "Type": null, "Note": "Transfer test attachment", "DocumentType": null } ], "Id": 245, "IsSuccess": true, "ErrorReason": "None", "ErrorCode": "None" }

I use code from Example 3:

var ignoredValues = new List { "Data.Id", "Note" }; CompareJsonFiles(ignoredValues);

private void CompareJsonFiles(List ignoredFields = null) { var jsonExpected = JsonConvert.DeserializeObject(File.ReadAllText(pathToJSON_1)); var jsonActual = JsonConvert.DeserializeObject(File.ReadAllText(pathToJSON_2));

var comparer = new Comparer();

if (ignoredFields != null)
    foreach (var field in ignoredFields)
        comparer.AddComparerOverride(field, DoNotCompareValueComparer.Instance);

comparer.Compare(jsonExpected, jsonActual, out IEnumerable<Difference> differences);

}

I expect having diff only for Id but in the result have difference for Id and Data.Id. If I specify CompareJsonFiles("Id", "Note"), it will ignore all Id, nested and non-nested ones. Could you please help me with ignoring nested elements as in this case? Seems that indexing by dot (Data.Id) doesn't work

ValeraT1982 commented 3 years ago

@4yck, you are right. Comparer doesn't support memberName with dots.

As a workaround, you can compare objects then filter differences by MemberPath

Does that work for you?

4yck commented 3 years ago

I guess it will be ok for me, thank you @ValeraT1982 !