dotnet/runtime
在 GitHub 查看JsonSerializer does not support parsing DateTime value '0001-01-01T00:00:00+01:00'
Open
#70,547 建立於 2022年6月10日
area-System.Text.Jsonenhancementhelp wanted
倉庫指標
- Star
- (17,886 star)
- PR 合併指標
- (平均合併 12天 11小時) (30 天內合併 661 個 PR)
描述
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