将 API 格式的 JSON 响应转换为 C# 并打印值

Convert API Response in JSON format to c# and print values

我有一个 API 回复,如下所示,

{
"Drivers.Pandemic.PeopleCount": {
"Value": "94",
"LastUpdatedTime": "2022-02-17T09:53:43.7418837+05:30",
"Status": "OK",
"HighLimit": 1000.0,
"LowLimit": 0.0,
"AlarmValue": null
},
"Drivers.Hospitality.Bollards": {
"Value": "1",
"LastUpdatedTime": "2022-02-17T09:53:42.5938448+05:30",
"Status": "OK",
"HighLimit": 1.0,
"LowLimit": 0.0,
"AlarmValue": null
},
"Drivers.Hospitality.FireAlarm": {
"Value": "0",
"LastUpdatedTime": "2022-02-17T09:53:02.1132161+05:30",
"Status": "OK",
"HighLimit": 1.0,
"LowLimit": 0.0,
"AlarmValue": "1"
}
}

我需要反序列化此响应并使用 C# 打印它。我该怎么做?

好吧,由于您从 API 获得的 JSON 有点奇怪,您需要对 'normal' 序列化采取一些不同的方法。

更好的方法是使用每个元素和字典获得 class 的帮助

Class:

public class Drivers
    {
        public string Value { get; set; }
        public DateTime LastUpdatedTime { get; set; }
        public string Status { get; set; }
        public double HighLimit { get; set; }
        public double LowLimit { get; set; }
        public object AlarmValue { get; set; }
    }

然后使用 Newtonsoft

反序列化
var myDeserializedDict= JsonConvert.DeserializeObject<Dictionary<string, Drivers>>(text);

之后你在词典中得到了一个 'normal' 集合,你可以随意使用它:

        foreach (KeyValuePair<string, Drivers> item in myDeserializedDict) 
        {
            Console.WriteLine(item.Key + " (Status): " + item.Value.Status.ToString());
            Console.WriteLine(item.Key + " (LastUpdated): " + item.Value.LastUpdatedTime.ToString());
[...]
        }