How do you compare two similar JSON array set ? I bet that is a scenario you might have across atleast once in your developer life. Let us say you have following two sets of JSONs.
Json Set 1
[
{
"SourceLocation":"England",
"DestinationLocation":"Spain",
"DeliveryDate":"9/12"
},
{
"SourceLocation":"England",
"DestinationLocation":"Germany",
"DeliveryDate":"9/12"
}
]
Json Set 2
[
{
"SourceLocation":"England",
"DestinationLocation":"Spain",
"DeliveryDate":"9/12"
},
{
"SourceLocation":"England",
"DestinationLocation":"Germany",
"DeliveryDate":"9/12"
},
{
"SourceLocation":"England",
"DestinationLocation":"Netherlands",
"DeliveryDate":"12/12"
}
]
The core idea here is to parse the JSON string to JArray’s and compare them.
public IEnumerable<String> CompareJsonArrays(string expected,string actual)
{
// Parse string to JArrays
JArray firstArray = JArray.Parse(expected);
JArray secondArray = JArray.Parse(actual);
// retrieve all children of JArray
var firstTokens = firstArray.Children();
var secondTokens = secondArray.Children();
// Compare the two set of collections using Custom comparer
var results = firstTokens.Except(secondTokens, new JTokenComparer())
.Concat(secondTokens.Except(firstTokens,new JTokenComparer()));
// Convert to Json String Representation
return results.Select(x=>x.ToString());
}
Where JTokenComparer
is defined as
public class JTokenComparer : IEqualityComparer<JToken>
{
public int GetHashCode(JToken co)
{
return1;
}
public bool Equals(JToken x1, JToken x2)
{
if (object.ReferenceEquals(x1, x2))
{
return true;
}
if (object.ReferenceEquals(x1, null) ||
object.ReferenceEquals(x2, null))
{
return false;
}
// Compares token and all child tokens.
return JToken.DeepEquals(x1,x2);
}
}
This would provide the difference in JSON string.
{
"SourceLocation": "England",
"DestinationLocation": "Netherlands",
"DeliveryDate": "12/12"
}