dotnet/runtime

JsonSerializer does not support parsing DateTime value '0001-01-01T00:00:00+01:00'

Open

#70.547 aberto em 10 de jun. de 2022

Ver no GitHub
 (3 comments) (0 reactions) (0 assignees)C# (5.445 forks)batch import
area-System.Text.Jsonenhancementhelp wanted

Métricas do repositório

Stars
 (17.886 stars)
Métricas de merge de PR
 (Mesclagem média 12d 11h) (661 fundiu PRs em 30d)

Description

Description

JsonSerializer throw the exception :

System.Text.Json.JsonException: 'The JSON value could not be converted to System.DateTime. Path: $

On a date it serialize itself when the value is '0001-01-01T00:00:00+01:00'

Reproduction Steps

  • Set your time zone to (UTC+01:00) Amsterdam, Berlin. Bern, Rome, Stockholm, Vienna
  • Launch the test :
[Fact]
public void JsonSerializerIssue()
{
    var expected = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Local);
    var serialized = JsonSerializer.Serialize(expected);
    var result = JsonSerializer.Deserialize<DateTime>(serialized);

    Assert.Equal(expected, result);
}

Expected behavior

No exception

Actual behavior

The exception

System.Text.Json.JsonException: 'The JSON value could not be converted to System.DateTime. Path: $

is thrown

Regression?

No response

Known Workarounds

We can workaround with a JsonConverter<DateTime> but it's ugly and as the serialization do not throw an exception the deserialization should.

class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString("s"));                
    }
}

Configuration

  • Which version of .NET is the code running on? netcoreapp3.1
  • What OS and version, and what distro if applicable? all, I guess
  • What is the architecture (x64, x86, ARM, ARM64)? x64
  • Do you know whether it is specific to that configuration? I don't think so

Other information

No response

Guia do colaborador