.Net Core 3.0 TimeSpan deserialization error - Fixed in .Net 5.0

后端 未结 3 2196
抹茶落季
抹茶落季 2021-02-13 23:27

I am using .Net Core 3.0 and have the following string which I need to deserialize with Newtonsoft.Json:

{
    \"userId\": null,
    \"accessToken\": null,
    \         


        
3条回答
  •  走了就别回头了
    2021-02-13 23:52

    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;
    }
    

提交回复
热议问题