我正在尝试反序列化以下 JSON
{"serverTime":1613967667240}
进入下一个类的对象
public class ApiServerTime
{
[JsonPropertyName("serverTime")]
public DateTime ServerTime
{
get;
private set;
}
}
使用以下命令:
JsonSerializer.Deserialize<ApiServerTime>(jsonString);
但生成的对象包含 ServerTime == DateTime.MinValue
。我做错了什么?
最佳答案
本着构建更好的捕鼠器的精神,这里的实现支持..
- 以秒或毫秒为单位的 Unix 时间。假设:秒 < 9999 年(最大日期时间)和毫秒 > 1978。
- 可为空的日期时间
public class UnixToNullableDateTimeConverter : JsonConverter<DateTime?>
{
public override bool HandleNull => true;
public bool? IsFormatInSeconds { get; set; } = null;
public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TryGetInt64(out var time))
{
// if 'IsFormatInSeconds' is unspecified, then deduce the correct type based on whether it can be represented in the allowed .net DateTime range
if (IsFormatInSeconds == true || IsFormatInSeconds == null && time > _unixMinSeconds && time < _unixMaxSeconds)
return DateTimeOffset.FromUnixTimeSeconds(time).LocalDateTime;
return DateTimeOffset.FromUnixTimeMilliseconds(time).LocalDateTime;
}
return null;
}
public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) => throw new NotSupportedException();
private static readonly long _unixMinSeconds = DateTimeOffset.MinValue.ToUnixTimeSeconds() - DateTimeOffset.UnixEpoch.ToUnixTimeSeconds(); // -62_135_596_800
private static readonly long _unixMaxSeconds = DateTimeOffset.MaxValue.ToUnixTimeSeconds() - DateTimeOffset.UnixEpoch.ToUnixTimeSeconds(); // 253_402_300_799
}
关于c# - 使用 System.Text.Json 反序列化 Json 时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66310421/