You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何反序列化含日期型属性名的JSON数据?

动态日期属性JSON的强类型反序列化实现

针对你提供的这种属性名为动态日期的JSON结构,以下是两种常用.NET序列化库的实现方案:

方案一:使用Newtonsoft.Json(Json.NET)

直接将watts字段定义为Dictionary<DateTime, int>,序列化库会自动将动态日期键转换为DateTime类型,对应的值转换为int:

1. 定义强类型类

public class PowerData
{
    public Dictionary<DateTime, int> Watts { get; set; }
}

2. 反序列化代码

string json = @"{""watts"": {
        ""2022-12-19 08:14:00"": 0,
        ""2022-12-19 09:00:00"": 48,
        ""2022-12-20 15:44:00"": 0
    }}";

var powerData = Newtonsoft.Json.JsonConvert.DeserializeObject<PowerData>(json);

如果JSON里的日期格式有特殊情况,可通过配置序列化参数指定格式:

var settings = new Newtonsoft.Json.JsonSerializerSettings
{
    DateFormatString = "yyyy-MM-dd HH:mm:ss"
};
var powerData = Newtonsoft.Json.JsonConvert.DeserializeObject<PowerData>(json, settings);

方案二:使用System.Text.Json(.NET Core/.NET 5+内置)

同样利用Dictionary<DateTime, int>接收动态键值对,需配置日期解析选项:

1. 定义强类型类

public class PowerData
{
    public Dictionary<DateTime, int> Watts { get; set; }
}

2. 反序列化代码

string json = @"{""watts"": {
        ""2022-12-19 08:14:00"": 0,
        ""2022-12-19 09:00:00"": 48,
        ""2022-12-20 15:44:00"": 0
    }}";

var options = new System.Text.Json.JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    DateTimeFormat = new System.Text.Json.DateTimeFormatInfo
    {
        FullDateTimePattern = "yyyy-MM-dd HH:mm:ss"
    }
};

var powerData = System.Text.Json.JsonSerializer.Deserialize<PowerData>(json, options);

进阶:转换为实体列表(可选)

如果希望将键值对转为更直观的实体列表,可在反序列化后手动转换:

// 以Json.NET为例,转换为实体列表
var powerRecords = powerData.Watts.Select(kv => new PowerRecord
{
    RecordTime = kv.Key,
    Watts = kv.Value
}).ToList();

// 定义实体类
public class PowerRecord
{
    public DateTime RecordTime { get; set; }
    public int Watts { get; set; }
}

内容的提问来源于stack exchange,提问作者Steve Borman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:50:23