.NET Core System.Text.Json 失败,并显示最小日期时间和 UTC 偏移量

.NET Core System.Text.Json fails with min datetime and UTC offset

提问人:Skami 提问时间:9/30/2019 最后编辑:Heretic MonkeySkami 更新时间:9/14/2023 访问量:2574

问:

我一直在从 2.2 迁移到 3.0,到目前为止,一切都非常顺利,但是当用新的 System.Text.Json 替换 Newtonsoft 时,我遇到了以下问题。

尝试使用 UTC 偏移量反序列化 DateTime 最小值时,它会引发以下异常

未处理的异常。System.Text.Json.JsonException:JSON 值 无法转换为 System.DateTime。路径:$。创建日期 | 行号:2 |BytePositionInLine:43

例:

using System;
using Newtonsoft.Json;      

class Program
{
    static void Main(string[] args)
    {
        var json = "{\"MyDateTime\": \"0001-01-01T00:00:00+01:00\"}";
                
        var newtonDeserialized = JsonConvert.DeserializeObject<Class>(json);

        //Bad things happen here.
        var systemDeserialized =  System.Text.Json.JsonSerializer.Deserialize<Class>(json);
        
        Console.WriteLine(newtonDeserialized.MyDateTime);
        Console.WriteLine(systemDeserialized.MyDateTime);
    }
}

class Class
{
    public DateTime MyDateTime {get; set;}
}

在线示例可以在这里找到 Fiddle.

我想我可以编写自己的 DateTime 序列化器,但必须有一种更简单/更干净的方法来完成 Newtonsoft 所做的,而无需任何配置。

这发生在 3.0.100、3.1.500、5.0.100、6.0.100 和 7.0.100 上

C# JSON 日期时间 net-core-3.0 system.text.json

评论

1赞 Fildor 9/30/2019
你真的需要那个日期吗?我猜它正试图在路上的某个地方应用偏移量,然后它无法创建“0000-12-31T23:00:00”......棘手。。。
2赞 DavidG 9/30/2019
有趣的是,它会正确地反序列化,但不会。不管是还是.0001-01-01T00:00:00+00:000001-01-01T00:00:00+01:00DateTimeDateTimeOffset
3赞 Peter Hull 9/30/2019
我做了一些闲逛,似乎它最终会到达这里:github.com/dotnet/corefx/blob/... - 请注意评论说年份必须是 0001 到 9999。这可能是一个错误,因为ISO8601没有该限制(我认为)。
1赞 Matt Johnson-Pint 10/1/2019
重要的不是 ISO 8601 的范围,而是 和 的支持范围。DateTimeOffsetDateTime
2赞 dbc 12/25/2021
既然 实际上早于 ,有人可能会问:为什么 Newtonsoft 可以成功地解析它?事实证明,Json.NET 有特定的代码来限制时区,以便日期时间值不会超出最小值和最大值 - 基于时区是UTC的东部还是西部。为此,他们必须编写自己的解析器;请参阅 DateTimeUtils.TryParseDateTimeIso()。"0001-01-01T00:00:00+01:00"DateTime.MinValue

答: 暂无答案