I am using .Net Core 3.0 and have the following string which I need to deserialize with Newtonsoft.Json:
{
\"userId\": null,
\"accessToken\": null,
\
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());
});
...
}
}