skip to Main Content

I wanna compare two nested JSON objects and get differences between theme like add/remove and change value.

I used JsonDiffer but when I remove one of objects from first or middle of an Array, it detected to change all of the objects.

Pay attention to simple example of my problem please:

The original JSON object is:

{
    "Array": [
       {
          "number": "111",
          "Weight": 76
        },
        {
          "number": "222",
          "Weight": 77
        },
        {
          "number": "333",
          "Weight": 75
        }
      ]
}

and the new is:

{
    "Array": [
        {
          "number": "222",
          "Weight": 77
        },
        {
          "number": "333",
          "Weight": 75
        }
      ]
}

In this sample JsonDiffer returned all objects in array was changed! In the event that should be returned 111 was removed only.

2

Answers


  1. Chosen as BEST ANSWER

    I finally got the answer to my question with the help of chatGBT

    If you need a more dynamic approach, you can use a dictionary-based comparison instead of a fixed model. Let's modify the solution to handle dynamic JSON objects.

    1. Deserialize your JSON strings into dictionaries:
    string json1 = "[{"number": "111","Weight": 76 },{"number": "222","Weight": 77},{"number": "333","Weight": 75}]";
    string json2 = "[{"number": "222","Weight": 77 }, {"number": "333","Weight": 75}]";
    
    var dict1 = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>[]>(json1);
    var dict2 = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>[]>(json2);
    
    1. Compare the dictionaries to find differences:
    var added = dict1.Except(dict2, new DictionaryComparer()).ToList();
    var removed = dict2.Except(dict1, new DictionaryComparer()).ToList();
    
    1. Implement a custom comparer for dictionaries:
    public class DictionaryComparer : IEqualityComparer<Dictionary<string, object>>
    {
        public bool Equals(Dictionary<string, object> x, Dictionary<string, object> y)
        {
            if (x == null || y == null)
                return false;
    
            return x.Keys.SequenceEqual(y.Keys) && x.Values.SequenceEqual(y.Values);
        }
    
        public int GetHashCode(Dictionary<string, object> obj)
        {
            unchecked
            {
                int hash = 17;
                foreach (var kvp in obj)
                {
                    hash = hash * 23 + kvp.Key.GetHashCode();
                    hash = hash * 23 + (kvp.Value?.GetHashCode() ?? 0);
                }
                return hash;
            }
        }
    }
    

    In this updated solution, the DictionaryComparer compares dictionaries based on their keys and values. The added list will contain the objects present in the first dictionary but not in the second, and the removed list will contain the opposite.

    Remember to adjust the comparison logic if your JSON objects have more complex structures or nested arrays. Feel free to adapt this approach to your specific needs.

    Let me know if you have any further questions or need additional assistance! 😊


  2. Check this code:

    Model Class:

    public class MyModel
    {
        public string number { get; set; }
        public int Weight { get; set; }
    }
    

    and the code:

    string json1 = "[{"number": "111","Weight": 76 },{"number": "222","Weight": 77},{"number": "333","Weight": 75}]";
    string json2 = "[{"number": "222","Weight": 77 }, {"number": "333","Weight": 75}]";
    
    var Array_json1 = System.Text.Json.JsonSerializer.Deserialize<MyModel[]>(json1);
    var Array_json2 = System.Text.Json.JsonSerializer.Deserialize<MyModel[]>(json2);
    
    var Result = Array_json1.Where(x => !Array_json2.Any(y => x.number == y.number && x.Weight == y.Weight));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search