Banshee
Banshee

Reputation: 15807

System.Text.Json.Deserialize can still not handle TimeSpan in .NET Core 5?

I have the following TimeSpan JSON string genereated from JsonSerilizer.Serialize<TimeSpan>(MyTymeSpan); :

jsonString= {"Ticks":1770400500000,"Days":2,"Hours":1,"Milliseconds":50,"Minutes":10,"Seconds":40,"TotalDays":2.0490746527777777,"TotalHours":49.177791666666664,"TotalMilliseconds":177040050,"TotalMinutes":2950.6675,"TotalSeconds":177040.05}

When executing this :

JsonSerializer.Deserialize<T>(jsonString);

I get a TimeSpan that is 0?

Some articles says that this should be fixed in .NET Core 5 so why do I get 0?

Regards

Upvotes: 0

Views: 487

Answers (2)

Banshee
Banshee

Reputation: 15807

System.Text.Json.Deserialize will not handle TimeSpan in Core 5 and because of my environment it was better to just revert back to Newtonsofts version for now. But from what I understand the .NET version is a lot faster so as soon as it can handle the types correctly it might be worth migrating.

Upvotes: 0

Blindy
Blindy

Reputation: 67382

No, not out of the box. In fact that mess you're getting when serializing is broken because it stores the same value multiple times (the Total* values), and useless information at the beginning.

You have two options:

  1. Serialize and deserialize the Ticks property. That is enough to build a TimeSpan in a cross-platform way. Don't use the Total* properties because they lose information due to resolution, Ticks is a raw 64-bit integer that fully represents how much resolution the .Net specs give the TimeSpan type, and it will not change.

  2. Write a custom JsonConverter that serializes the Ticks property for TimeSpan. A bit more code to set up, but then you can just use TimeSpan directly in your class.

Upvotes: 0

Related Questions