c# - 使用 System.Text.Json 反序列化 Json 时间戳

标签 c# json datetime system.text.json

我正在尝试反序列化以下 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/

相关文章:

c# - WebAPI 暂时从 OnActionExecuted 覆盖 JsonFormatter

c# - 在 C# 中取消选择列表框项

java - JSON 格式的数组列表

c# - 如何从日期列中排除时间

c# - 为 Node.js 应用程序创建 COM API 或类似的 API

json - JWT(json web token) 可以完全取代 Session 吗?

python - 如何在Python中将字符串添加到JSON列表中

c# - 从 DateTime (utc) 和 TimeZoneInfo 获取 DateTimeOffset

php - 计算出勤时间戳2

c# - C++ 到 C# worker 类(Class)的 union