Home > OS >  How do I deserialize Json that has date based property names?
How do I deserialize Json that has date based property names?

Time:12-21

I have the following Json snippet being returned from an API. I want to deserialize into a Typed class however the property names are dates so they change with each call.

How do I do this?

"watts": {
        "2022-12-19 08:14:00": 0,
        "2022-12-19 09:00:00": 48,
        "2022-12-19 10:00:00": 114,
        "2022-12-19 11:00:00": 140,
        "2022-12-19 12:00:00": 140,
        "2022-12-19 13:00:00": 132,
        "2022-12-19 14:00:00": 105,
        "2022-12-19 15:00:00": 53,
        "2022-12-19 15:44:00": 0,
        "2022-12-20 08:14:00": 0,
        "2022-12-20 09:00:00": 230,
        "2022-12-20 10:00:00": 383,
        "2022-12-20 11:00:00": 453,
        "2022-12-20 12:00:00": 453,
        "2022-12-20 13:00:00": 384,
        "2022-12-20 14:00:00": 238,
        "2022-12-20 15:00:00": 81,
        "2022-12-20 15:44:00": 0
    }

CodePudding user response:

the easiest way is to deserialize to a dictionary

Dictionary<DateTime, int> wattsDict = JObject.Parse(json)["watts"]
                                      .ToObject<Dictionary<DateTime, int>>();

but if you need more typed data, you can create a list

List<Watt> watts = ((JObject)JObject.Parse(json)["watts"]).Properties()
                                   .Select(i => new Watt { Date = DateTime.Parse(i.Name), 
                                                           Quantity = (int)i.Value }
                                    ).ToList();

public class Watt
{
    public DateTime Date { get; set; }
    public int Quantity { get; set; }
}
  • Related