Home > Enterprise >  How would i compare two JSON files and get the specific objects which differs using C#?
How would i compare two JSON files and get the specific objects which differs using C#?

Time:12-03

I got two JSON files containing mostly identical data, but there might be objects that is only present in one of the files. How would i go about identifying these specific objects?

Example:
JSON 1:

[
  {
    "SourceLocation": "England",
    "DestinationLocation": "Spain",
    "DeliveryDate": "9/12"
  },
  {
    "SourceLocation": "England",
    "DestinationLocation": "Germany",
    "DeliveryDate": "9/12"
  }
]

JSON 2:

[
  {
    "SourceLocation": "England",
    "DestinationLocation": "Spain",
    "DeliveryDate": "9/12"
  },
  {
    "SourceLocation": "England",
    "DestinationLocation": "Germany",
    "DeliveryDate": "9/12"
  },
  {
    "SourceLocation": "England",
    "DestinationLocation": "Netherlands",
    "DeliveryDate": "12/12"
  }
]

Desired result:

[
 {
    "SourceLocation": "England",
    "DestinationLocation": "Netherlands",
    "DeliveryDate": "12/12"
  }
]

CodePudding user response:

You could convert the string representation of Json to JArrays (I see you have list of items) and compare each item. For example (inline comments included for code),


 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)
    {
        return 1;
    }

    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);
    }
}

Now you could compare the two json strings as following

CompareJsonArrays(json1,json2);

The Custom Comparer uses JToken.DeepEquals() for retrieving difference between tokens.

  • Related