8

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

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

未处理的异常。System.Text.Json.JsonException:无法将 JSON 值转换为 System.DateTime。路径:$.DateCreated | 行号:2 | 字节位置行内: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.1006.0.100

4

0 回答 0