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

后端 未结 3 2175
抹茶落季
抹茶落季 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:46

    My solution is to use custom converter, but with explicitly specified standard non culture-sensitive TimeSpan format specifier .

    public class JsonTimeSpanConverter : JsonConverter
    {
        public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return TimeSpan.ParseExact(reader.GetString(), "c", CultureInfo.InvariantCulture);
        }
    
        public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("c", CultureInfo.InvariantCulture));
        }
    }
    

    Then register it in the Startup for the HostBuilder:

    public class Startup
    {
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            ...
            services
                ...
                .AddJsonOptions(opts =>
                {
                    opts.JsonSerializerOptions.Converters.Add(new JsonTimeSpanConverter());                    
                });
            ...
        }
    }
    

提交回复
热议问题