Home > Back-end >  Convert API Response in JSON format to c# and print values
Convert API Response in JSON format to c# and print values

Time:02-24

I have an API response like below,

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

I need to deserialize this response and print it using c#. How can I do this?

CodePudding user response:

Well, as the JSON you're getting from the API is a little WEIRD youn need a little different aproach to the 'normal' serializacion.

Better aproach is to get help of a class with each element and a dictionary

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

and then deserialize using Newtonsoft

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

After this you got a 'normal' collection inside the Dictionary and can use it as you wish:

        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());
[...]
        }

CodePudding user response:

use this For Table

JsonConvert.DeserializeObject<System.Data.DataTable>(JsoneFile);

  • Related