C#将JSON数组反序列化为列表时items字段为null,求解决
问题分析与解决方案
你的核心问题是C#类结构和JSON数据格式不匹配:
- JSON中的每个对象包含
TagNumber、TagName,以及四个平行数组字段(TimeStamp、Value、Confidence、Sequence) - 你定义的
Response类里的items字段在JSON中不存在,所以反序列化后必然为null
下面提供两种可行的解决方式:
方式一:直接匹配JSON结构定义类
先定义和JSON完全对应的类,确保字段名、类型完全匹配:
public class TagData { public int TagNumber { get; set; } public string? TagName { get; set; } // JSON中无Units、Status字段,反序列化后会取默认值,不需要可删除 public string? Units { get; set; } public int Status { get; set; } public List<string>? TimeStamp { get; set; } public List<int>? Value { get; set; } public List<int>? Confidence { get; set; } public List<int>? Sequence { get; set; } }
执行反序列化:
var result = JsonConvert.DeserializeObject<List<TagData>>(responseContent);
如果需要将平行数组转换为Item列表循环处理,可在反序列化后手动映射:
if (result != null && result.Any()) { var firstTag = result[0]; // 确保所有数组非空且长度一致 if (firstTag.TimeStamp != null && firstTag.Value != null && firstTag.Confidence != null && firstTag.Sequence != null && firstTag.TimeStamp.Count == firstTag.Value.Count && firstTag.TimeStamp.Count == firstTag.Confidence.Count && firstTag.TimeStamp.Count == firstTag.Sequence.Count) { List<Item> items = new List<Item>(); for (int i = 0; i < firstTag.TimeStamp.Count; i++) { // 指定时间格式避免解析错误 DateTime timestamp = DateTime.ParseExact( firstTag.TimeStamp[i], "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); items.Add(new Item { TimeStampValue = timestamp, Value = firstTag.Value[i], ConfidenceValue = firstTag.Confidence[i], SequenceValue = firstTag.Sequence[i] }); } // 循环处理items列表 foreach (var item in items) { // 你的业务逻辑 } } }
方式二:直接转换为你需要的Response结构
如果希望直接得到包含items列表的Response对象,可先反序列化到匹配JSON的类,再映射为目标结构:
// 先反序列化到匹配JSON的类 var tagDataList = JsonConvert.DeserializeObject<List<TagData>>(responseContent); // 映射为你需要的Response结构 var responseList = tagDataList?.Select(tag => new Response { TagNumber = tag.TagNumber, TagName = tag.TagName, Units = tag.Units, Status = tag.Status, items = tag.TimeStamp?.Select((ts, index) => new Item { TimeStampValue = DateTime.ParseExact(ts, "MM/dd/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture), Value = tag.Value?[index], ConfidenceValue = tag.Confidence?[index], SequenceValue = tag.Sequence?[index] }).ToList() }).ToList();
这样responseList中的items就会被正确填充,可直接循环处理。
内容的提问来源于stack exchange,提问作者kkeith1723
相关产品推荐
相关产品推荐

