Search code examples
c#jsonsortingienumerableassert

How to sort and compare two JSON arrays in C#?


I have two JSON arrays as below

# Array1

[
  {
    "objectId": "34fc6a0c-be91-4a6d-b5dd-20ae347085c7",    
    "model": "robotics.energy",
    "timestamp": "2020-08-07T12:36:40.697Z",
    "value": 2.0
  },
  {
    "objectId": "34fc6a0c-be91-4a6d-b5dd-20ae347085c7",    
    "model": "robotics.energy",
    "timestamp": "2020-08-07T12:36:40.697Z",
    "value": 4459.477340033425
  }
]

# Array2

[
 {
    "model": "robotics.energy",
    "objectId": "34fc6a0c-be91-4a6d-b5dd-20ae347085c7",       
    "timestamp": "2020-08-07T12:36:40.697Z",
    "value": 4459.477340033425
  },
  {
    "timestamp": "2020-08-07T12:36:40.697Z",
    "objectId": "34fc6a0c-be91-4a6d-b5dd-20ae347085c7",    
    "model": "robotics.energy",   
    "value": 2.0
  }
]

I want to assert those two arrays are equal or not.

I tried s below. But it fails since order of the elements are different

var jarray1 = JArray.Parse(Array1);
var jarray2 = JArray.Parse(Array2);
JArray.DeepEquals(jarray1, jarray2); 

Tried as below anyway it throws error as Icomparable interface is not implemented.

Enumerable.SequenceEqual(jarray1 .OrderBy(t => t), jarray2.OrderBy(t => t)).Should().BeTrue();   

                 

Is there any easy solution exist?

I thought of converting it to string then sort it and verify it. But I felt that's not good way.


Solution

  • Created classes as below for de-serializing it.

    public class Telemetry
        {
            [JsonProperty("model")]
            public string Model { get; set; }
    
            [JsonProperty("objectId")]
            public string ObjectId { get; set; }
    
            [JsonProperty("timestamp")]
            public string Timestamp { get; set; }
    
            [JsonProperty("value")]
            public object Value { get; set; }     
        }
    
    public class TelemetryRoot
        {
            public List<Telemetry> Telemetries { get; set; }
        }
    

    Then did as below to compare the deserialized objects.

    var array1Obj = JsonConvert.DeserializeObject<List<TelemetryRoot>>(Array1);
    var array2Obj = JsonConvert.DeserializeObject<List<TelemetryRoot>>(Array2);
    array1Obj.Should().BeEquivalentTo(array2Obj);     //using fluent assertions