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

C#如何反序列化含日期作为属性名的IoT JSON数据?

解决C#反序列化含日期属性名的JSON对象问题

你的问题核心是类结构与JSON结构不匹配:JSON里的statisticsPerDay是一个动态键值对集合(键为日期字符串,值是包含lora数据的对象),但你定义的StatisticsPerDay类直接期望一个lora属性,完全无法对应,因此反序列化后该对象为null。

正确的类结构定义

需要将statisticsPerDay的类型改为Dictionary<string, DailyLoraData>(若要自动解析日期为DateTime,可替换为Dictionary<DateTime, DailyLoraData>),同时补充对应的嵌套类:

public class DeviceStates
{
    [JsonProperty("tenantId")]
    public string TenantId { get; set; }

    [JsonProperty("tenantName")]
    public string TenantName { get; set; }

    [JsonProperty("statisticsPerDay")]
    // 用字典接收动态日期键的对象集合
    public Dictionary<string, DailyLoraData> StatisticsPerDay { get; set; }
}

// 单个日期对应的lora数据容器
public class DailyLoraData
{
    [JsonProperty("lora")]
    public LoraStats Lora { get; set; }
}

public class LoraStats
{
    [JsonProperty("counters")]
    public LoraCounters Counters { get; set; }
}

public class LoraCounters
{
    [JsonProperty("virtualMsgIn")]
    public int VirtualMsgIn { get; set; }

    [JsonProperty("numberOfSources")]
    public int NumberOfSources { get; set; }

    [JsonProperty("msgIn")]
    public int MsgIn { get; set; }

    [JsonProperty("bytesIn")]
    public int BytesIn { get; set; }
}

反序列化代码

保持你原有的调用即可,现在类结构与JSON完全匹配:

var result = JsonConvert.DeserializeObject<DeviceStates>(data);

(可选)将日期键直接解析为DateTime类型

Newtonsoft.Json会自动识别符合格式的日期字符串,只需修改DeviceStates中的对应属性:

[JsonProperty("statisticsPerDay")]
public Dictionary<DateTime, DailyLoraData> StatisticsPerDay { get; set; }

验证反序列化结果

可以通过遍历字典查看数据:

foreach (var dailyStats in result.StatisticsPerDay)
{
    Console.WriteLine($"日期:{dailyStats.Key}");
    Console.WriteLine($"当日消息数:{dailyStats.Value.Lora.Counters.MsgIn}");
    Console.WriteLine($"当日字节数:{dailyStats.Value.Lora.Counters.BytesIn}");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:55:32