I’m having trouble converting a json into a timeSpan in C#, I have different json. Here are a few examples:
{
‘seconds’: 60
}
{
‘hours’: 11
}
{
‘years: 5
}
If you have any ideas I’d be grateful
Thanks
I’m looking to dynamically create timeSpans based on the returned Json.
For example :
As input:
{
‘seconds’: 60
}
=> Output:
new TimeSpan( 0, 0, 0, 60, 0 )
2
Answers
Create your own class do deserialize to. Then convert that to a
TimeSpan
.The JsonTimeSpanConverter class contains a method ConvertJsonToTimeSpan that takes a JSON string as input and extracts the relevant time components (days, hours, minutes, seconds, and milliseconds) to create a TimeSpan object. The code uses the System.Text.Json namespace for parsing JSON data.