I am using .Net Core 3.0 and have the following string which I need to deserialize with Newtonsoft.Json:
{
\"userId\": null,
\"accessToken\": null,
\
Not sure if it is the nullable TimeSpan that I am using, but even with .NET 5.0 I am still not able to deserialize a TimeSpan when using System.Text.Json
.
In any case, here is a solution that I have used in several models for custom serialization. Note that the [NotMapped]
attribute is only required if you are planning to use the class as a database model.
using System.Text.Json.Serialization;
using System.ComponentModel.DataAnnotations.Schema;
// Add your namespace and class declarations
[JsonIgnore]
public TimeSpan? MyTimeSpan { get; set; }
[NotMapped]
public long MyTimeSpanSerializer
{
get => MyTimeSpan?.Ticks ?? -1;
set => MyTimeSpan = value >= 0 ? new TimeSpan(value) : (TimeSpan?)null;
}