WPF使用Json.NET如何将JSON多对象反序列化并存入List?
Json.NET 反序列化实现方案
1. 前置准备
- 首先通过NuGet包管理器安装
Newtonsoft.Json到你的项目中 - 补全JSON结构对应的根节点模型类,你当前仅定义了
Item类,缺少外层节点映射:
public class Root { public List<Item> Items { get; set; } }
2. 完整反序列化与遍历逻辑
修改后的代码如下:
public partial class ItemHandler : Page { string itemsJson; // 存储所有Item的集合 public List<Item> ItemList { get; set; } // 若需要通过Name快速查找条目,可额外定义字典 public Dictionary<string, Item> ItemDict { get; set; } public ItemHandler() { InitializeComponent(); itemsJson = JsonHandler.ReadItems(); // 反序列化JSON:JSON根节点是数组,所以泛型类型指定为List<Root> var rootList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Root>>(itemsJson); // 提取所有Item到统一集合 ItemList = new List<Item>(); foreach (var root in rootList) { if (root.Items != null) { ItemList.AddRange(root.Items); } } // 遍历Item集合获取Name属性,替换为你的业务逻辑即可 foreach (var item in ItemList) { var currentItemName = item.Name; // 你的业务代码... } // 可选:生成Name为键的字典,后续可直接通过名称取值 ItemDict = ItemList.ToDictionary(item => item.Name); // 后续使用示例:var targetItem = ItemDict["Item 0"]; } } public class Item { public string Name { get; set; } }
逻辑说明
- 你的JSON结构根节点是数组,数组内每个对象包含
Items子集合,所以反序列化时要先匹配外层的数组结构 - 调用
JsonConvert.DeserializeObject方法时指定对应的泛型类型即可完成属性自动映射 - 提取所有Item到统一集合后,直接遍历即可访问每个对象的
Name属性,如需高频按名称检索可转换为字典结构提升查询效率
内容的提问来源于stack exchange,提问作者Lwiss
相关产品推荐
相关产品推荐

