System.Text.Json 反序列化时间的问题
下面的 .NET 6 C# 代码,运行时会报错
var json = System.Text.Json.JsonSerializer.Serialize(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
Console.WriteLine(json);
var dt = System.Text.Json.JsonSerializer.Deserialize<DateTime>(json);
Console.WriteLine(dt);
报错信息
System.Text.Json.JsonException: The JSON value could not be converted to System.DateTime. Path: $ | LineNumber: 0 | BytePositionInLine: 21.
---> System.FormatException: The JSON value is not in a supported DateTime format.
请问如何解决?
回答
通过下面的自定义 DateTimeJsonConverter 解决了
public class DateTimeJsonConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> DateTime.Parse(reader.GetString() ?? string.Empty);
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString("o"));
}
反序列化示例代码
var dt = JsonSerializer.Deserialize<DateTime>(
"\"04/01/2018 09:51:00\"",
new JsonSerializerOptions { Converters = { new DateTimeJsonConverter() } });