Ska*_*ami 7 c# datetime json .net-core-3.0 system.text.json
我一直在从 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;}
}
Run Code Online (Sandbox Code Playgroud)
在线示例可以在这里找到Fiddle。
我想我可以编写自己的 DateTime 序列化程序,但必须有一种更简单/更简洁的方法来完成 Newtonsoft 所做的工作而无需任何配置。
这发生在3.0.100,3.1.500并且5.0.100