如何在 C# 中对两个 JSON 数组进行排序和比较?

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

我有两个 JSON 数组如下

#数组1

[
  {
    "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
  }
]

#数组2

[
 {
    "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
  }
]

我想断言这两个数组是否相等。

我在下面试过了。但它失败了,因为元素的顺序不同

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

尝试如下,无论如何它会抛出错误,因为 Icomparable 接口未实现。

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

                 

有什么简单的解决办法吗?

我想把它转换成字符串然后排序并验证它。但是我觉得这不是个好办法

为 de-serializing 创建了如下 类。

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

然后如下所示比较反序列化的对象。

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