C#如何用foreach循环读取JSON文件中AA、BB、CC对象数组的指定数据
问题原因
你的代码存在以下几处核心问题导致无法正常运行:
- 存储数据的
ArrayAA/ArrayBB/ArrayCC未做初始化,直接调用Add方法会触发空引用异常 - 遍历字典时没有根据Key区分数据类型,所有值同时写入三个集合,逻辑完全错误
- 存在重复反序列化的冗余操作,且代码中
json和JSONdata两个变量混淆 - 未做类型转换,JSON中的
value字段是字符串格式,无法直接赋值给DateTime/double类型的集合元素
实现方案
第一步:定义匹配JSON结构的实体类
public class MyObject { [JsonProperty("ts")] public long TS { get; set; } [JsonProperty("value")] public string Value { get; set; } }
第二步:初始化存储集合
// 初始化外层集合,数量和devices保持一致 List<List<DateTime>> ArrayAA = new List<List<DateTime>>(); List<List<double>> ArrayBB = new List<List<double>>(); List<List<double>> ArrayCC = new List<List<double>>(); // 初始化每个device对应的内层子集合 for (int i = 0; i < devices.Count; i++) { ArrayAA.Add(new List<DateTime>()); ArrayBB.Add(new List<double>()); ArrayCC.Add(new List<double>()); }
第三步:修正数据读取逻辑
for (int i = 0; i < devices.Count; i++) { // 替换为当前device对应的JSON字符串 string currentDeviceJson = 获取当前device的JSON数据; var myDictionary = JsonConvert.DeserializeObject<Dictionary<string, List<MyObject>>>(currentDeviceJson); if (myDictionary == null) continue; // 读取AA类的时间值 if (myDictionary.TryGetValue("AA", out var aaData)) { foreach (var item in aaData) { if (DateTime.TryParse(item.Value, out var dateVal)) { ArrayAA[i].Add(dateVal); } } } // 读取BB类的数值 if (myDictionary.TryGetValue("BB", out var bbData)) { foreach (var item in bbData) { if (double.TryParse(item.Value, out var numVal)) { ArrayBB[i].Add(numVal); } } } // 读取CC类的数值 if (myDictionary.TryGetValue("CC", out var ccData)) { foreach (var item in ccData) { if (double.TryParse(item.Value, out var numVal)) { ArrayCC[i].Add(numVal); } } } }
以上逻辑可实现一次性分别读取三类数据到对应集合,额外增加的类型校验可以避免JSON值格式异常导致程序崩溃。
内容的提问来源于stack exchange,提问作者ingezone
相关产品推荐
相关产品推荐

