在 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# 应用更方便地处理时间信息。

相关推荐
程序员爱钓鱼44 分钟前
Go语言实战案例-判断一个数是否为质数
后端·google·go
程序员爱钓鱼1 小时前
Go语言实战案例-读取本地文本文件内容
后端·google·go
斯是 陋室9 小时前
在CentOS7.9服务器上安装.NET 8.0 SDK
运维·服务器·开发语言·c++·c#·云计算·.net
mCell9 小时前
Go 并发编程基础:从 Goroutine 到 Worker Pool 实践
后端·性能优化·go
Python智慧行囊10 小时前
Flask 框架(一):核心特性与基础配置
后端·python·flask
inwith10 小时前
C#语法基础总结(超级全面)(二)
开发语言·c#
ん贤11 小时前
如何加快golang编译速度
后端·golang·go
摸鱼仙人~12 小时前
Spring Boot 参数校验:@Valid 与 @Validated
java·spring boot·后端
思无邪667513 小时前
从零构建搜索引擎 build demo search engine from scratch
后端
Littlewith13 小时前
Node.js:创建第一个应用
服务器·开发语言·后端·学习·node.js