How to compare two Json objects using C#

后端 未结 6 1812
我在风中等你
我在风中等你 2021-02-05 19:57

I have two Json objects as below need to be compared. I am using Newtonsoft libraries for Json parsing.

string InstanceExpected = jsonExpected;
string InstanceAc         


        
6条回答
  •  温柔的废话
    2021-02-05 20:38

    Made a non-recursive method which will remove twins - idea is to remove same elements from very similar JSONs, so that there will remain only different nodes in each object:

    public void RemoveTwins(ref BreadthFirst bf1, ref BreadthFirst bf2) {
        JsonNode traversal = bf1.Next();
        Boolean removed = false;
        do {
            if (!removed) {
                if (bf2.Current != null) while (bf1.Level == bf2.Level && bf2.Next() != null) ;
                if (bf2.Current != null) while (bf1.Level != bf2.Level && bf2.Next() != null) ;
                else bf2.Current = bf2.root;
            }
            else traversal = bf1.Next();
            if (bf2.Level < 0) bf2.Current = bf2.Root;
            do {
                removed = bf1.NextAs(bf1.src, bf2, bf2.src);
                if (removed && bf1.Orphan && bf2.Orphan) {
                    JsonNode same = bf1.Current.Parent;
                    traversal = bf1.RemoveCurrent();
                    same = bf2.Current.Parent;
                    bf2.RemoveCurrent();
                    bf1.UpdateLevel();
                    bf2.UpdateLevel();
                    if (traversal == null
                    || bf1.Root == null || bf2.Root == null
                    || (bf1.Level == 0 && bf1.Current.NodeBelow == null)) {
                        traversal = null;
                        break;
                    }
                } else
                if (!removed) {
                    break; 
                } else removed = false;
            } while (removed);
            if (!removed) traversal = bf1.Next();
        } while (traversal != null);
    }
    

    Complete code + parser on my GitHub (profile or below).
    Older CSV version which also sorts input mentioned in my question here How to compare big JSON's? (new one does not, so it could be very slow when one of objects has reversed order - it would be easier to sort during parsing or at least compare both neighbours of twins as first search step)

提交回复
热议问题