Json convert TimeSpan Error .Net Core 2.2

Viewed 502

i work with .net core 2.2, i tried to deserialize datas from WebApi but TimeSpan Type is not converted.

My InnerException is :{"Could not cast or convert from System.String to System.TimeSpan."}

My ErrorMessage is :{" Error converting value "PT20H20M" to type 'System.TimeSpan'. Path 'value[0].StartTime', line 1, position 179."}

the problem is on a member of my class: public TimeSpan StartTime { get; set; }

Can someone get the same error or can someone give me some ideas to how manage the problem.

Thanks !

1 Answers

Well, I guess the error is that the default converter does not know the format that you are trying to send in. You have to use a format that it understands or use a custom converter or use a string and convert it yourself afterwards.

If you run TimeSpan.Parse("PT20H20M") you will get an error that says it's not a valid format.

It seems that this call can get you a TimeSpan:

System.Xml.XmlConvert.ToTimeSpan("P2DT01H")

You can use a custom converter as described here or here (First one is for .net core 3).

Related