在 C# 中通过 JsonConvert.DeserializeObject 将时间戳转换为 DateTime

在使用 C# 和 Newtonsoft.Json 库进行 JSON 反序列化时,可能会遇到这样一种情况:JSON 文件中的时间字段是一个 long 类型的 Unix 时间戳,但你希望在 C# 类中将其映射为 DateTime 类型。本文记录如何通过自定义 JsonConverter 来实现这一转换。


一、问题场景

假设你的 JSON 文件如下:

复制代码
{ "getTime": 1672531200 }

其中 getTime 是一个 Unix 时间戳(以秒为单位的整数),但是在 C# 中你想将其映射为 DateTime 类型。如果直接使用 JsonConvert.DeserializeObject 进行反序列化,会因为类型不匹配导致错误。因此,我们需要一种方式将时间戳转换为 DateTime


二、解决方案:使用自定义 JsonConverter

通过继承 JsonConverter,我们可以自定义反序列化过程,将 long 类型的 Unix 时间戳正确转换为 DateTime

1. 编写自定义转换器
cs 复制代码
using Newtonsoft.Json;
using System;

public class UnixDateTimeConverter : JsonConverter<DateTime>
{
    // 反序列化时,将long类型的时间戳转换为DateTime
    public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Integer)
        {
            var timestamp = (long)reader.Value;
            return DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime; // 秒级时间戳转换为UTC时间
        }

        throw new JsonSerializationException("Unexpected token type when parsing date.");
    }

    // 序列化时,将DateTime转换为Unix时间戳
    public override void WriteJson(JsonWriter writer, DateTime value, JsonSerializer serializer)
    {
        var unixTimestamp = new DateTimeOffset(value).ToUnixTimeSeconds();
        writer.WriteValue(unixTimestamp);
    }
}
2. 在类中使用转换器

在需要反序列化时间戳的类上,为目标字段添加 [JsonConverter] 特性来指定我们定义的转换器:

cs 复制代码
using Newtonsoft.Json;
using System;

public class MyClass
{
    // 使用UnixDateTimeConverter将long时间戳转换为DateTime
    [JsonConverter(typeof(UnixDateTimeConverter))]
    public DateTime GetTime { get; set; }
}

三、示例代码:反序列化 JSON 数据

以下是完整的示例程序,将 JSON 中的时间戳转换为 DateTime

cs 复制代码
using Newtonsoft.Json;
using System;

class Program
{
    static void Main()
    {
        string json = "{\"getTime\":1672531200}"; // JSON 数据中的时间戳
        
        MyClass myObject = JsonConvert.DeserializeObject<MyClass>(json); // 反序列化
        
        Console.WriteLine($"输出 GetTime: {myObject.GetTime}"); // 打印结果
    }
}
输出示例:
cs 复制代码
输出 GetTime: 1/1/2023 12:00:00 AM

四、总结

通过自定义 JsonConverter,我们可以轻松将 JSON 中的 long 类型 Unix 时间戳转换为 C# 的 DateTime 类型。这种方法不仅能处理时间戳的反序列化,还支持在序列化时将 DateTime 转换回 Unix 时间戳,从而保证了数据格式的灵活性。

这种方案非常适用于需要与外部系统交互、并且时间戳使用 Unix 标准的项目。通过此方式,可以在不更改 JSON 数据格式的情况下,使 C# 应用更方便地处理时间信息。

相关推荐
摆烂工程师1 小时前
教你如何认证 Gemini 教育优惠的二次验证,薅个 1年的 Gemini Pro 会员
后端·程序员·gemini
绝无仅有2 小时前
未来教育行业的 Go 服务开发解决方案与实践
后端·面试·github
上位机付工2 小时前
2025年了,学C#上位机需要什么条件
c#·上位机·西门子
c#上位机2 小时前
wpf之Border
c#·wpf
程序员爱钓鱼2 小时前
Go语言实战案例- 命令行参数解析器
后端·google·go
心在飞扬2 小时前
Redis 介绍与 Node.js 使用教程
后端
milanyangbo3 小时前
“卧槽,系统又崩了!”——别慌,这也许是你看过最通俗易懂的分布式入门
分布式·后端·云原生·架构
AAA修煤气灶刘哥3 小时前
MySQL 查文本查哭了?来唠唠 ES 这货:从 “啥是 ES” 到 Java 撸代码,一篇整明白!
java·后端·elasticsearch
金銀銅鐵3 小时前
[Java] 浅析密封类(Sealed Classes) 在 class 文件中是如何实现的
java·后端
007php0073 小时前
Go语言面试:传值与传引用的区别及选择指南
java·开发语言·后端·算法·面试·golang·xcode