Ally
Ally

Reputation: 4942

How do I compare two DynamicJsonObjects to check they are equal?

I can't see how you can compare two DynamicJsobObjects. There is the method GetDynamicMemberNames which tells you what properties each has but how do you access the values of those properties?

I've arrived at this stub of a function but have no idea how to check the objects are the same. It stems from testing two json strings. One being a response from a web API, while the other being the expected result. I constructed the objects using Json.Decode(expectedJsonString) and Json.Decode(resultJsonString).

Function stub:

public static bool AreJsonObjectsEqual(DynamicJsonObject obj1, DynamicJsonObject obj2)
{
        return // ?
}

How do I compare the two objects to ensure they are equal?

Upvotes: 1

Views: 467

Answers (1)

Grundy
Grundy

Reputation: 13381

You can try something like this

public static bool AreJsonObjectsEqual(DynamicJsonObject obj1, DynamicJsonObject obj2)
{
    var memberNamesNotEqual = obj1.GetDynamicMemberNames().Except(obj2.GetDynamicMemberNames()).Any();
    if (!memberNamesNotEqual)
    {
       dynamic dObj1 = (dynamic)obj1;
       dynamic dObj2 = (dynamic)obj2;
       foreach (var memberName in obj1.GetDynamicMemberNames()){
           if(dObj1[memberName] != dObj2[memberName]) return false
       }
       return true
    }
    return memberNamesNotEqual;
}

Upvotes: 2

Related Questions