How to compare two Json objects using C#

后端 未结 6 1820
我在风中等你
我在风中等你 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:37

    In case you are looking for a light weight library to compares two JSON objects (or practically any serializable entities) You may use the following package, it (currently) uses Newtonsoft.Json JObjects and highlights the differences based on a simple convention (* modified, - removed, + added from/ to the second operand) as shown below.

    JSON 1

    {
      "name":"John",
      "age":30,
      "cars": {
        "car1":"Ford",
        "car2":"BMW",
        "car3":"Fiat"
      }
     }
    

    JSON 2

    {
      "name":"John",
      "cars": {
        "car1":"Ford",
        "car2":"BMW",
        "car3":"Audi",
        "car4":"Jaguar"
      }
     }
    

    Usage

    
     var j1 = JToken.Parse(Read(json1));
     var j2 = JToken.Parse(Read(json2));
    
     var diff = JsonDifferentiator.Differentiate(j1,j2);
    
    

    Result

    {
      "-age": 30,
      "*cars": {
        "*car3": "Fiat",
        "+car4": "Jaguar"
      }
    }
    

    https://www.nuget.org/packages/JsonDiffer

提交回复
热议问题