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
}
2
Answers
the easiest way is to deserialize to a dictionary
but if you need more typed data, you can create a list
I am not familiar with newtonsoft and it seem that newtonsoft has more features than the JsonSerializer. Nonetheless i wondered how the requirement above could be done with the "built-in" System.Text.Json.Serializer. And maybe others might find it usefull
The first thing i stumbled over was that
"2022-12-19 08:14:00"
could not be parsed out of the box,"2022-12-19T08:14:00"
it is parseable.GetWattsJson()
returns the json object with the changed date format.Using a
Dictionary<DateTime, int>
is the starting pointto later copy the values into the type
Watt
The copying is quite easy
Result in linqpad
Convert Date
This code show how to change the date format