如何在C#中反序列化含动态键的JSON数据?
正确的反序列化方法
方法一:修正类结构(适配动态键的items)
你原代码的问题在于Root类里的items用了List<Item>,但JSON中的items是字符串键对应Item对象的字典结构,而非数组。只需把items的类型改为Dictionary<string, Item>即可正常反序列化:
public class Item { public string price { get; set; } public double buy_order { get; set; } public string avg_price { get; set; } public string popularity_7d { get; set; } public string market_hash_name { get; set; } public string ru_name { get; set; } public string ru_rarity { get; set; } public string ru_quality { get; set; } public string text_color { get; set; } public string bg_color { get; set; } } public class Root { public bool success { get; set; } public int time { get; set; } public string currency { get; set; } // 替换为字典类型适配动态键 public Dictionary<string, Item> items { get; set; } }
反序列化调用代码:
string jsonString = "你的目标JSON字符串"; Root result = JsonConvert.DeserializeObject<Root>(jsonString); // 遍历items中的动态键值对 foreach (var kvp in result.items) { string uniqueItemKey = kvp.Key; // 如"186150629_143865972" Item itemDetail = kvp.Value; // 按需处理item数据 }
方法二:不手动创建类结构(动态解析)
如果不想提前定义类,可以用dynamic或JObject实现无类反序列化:
用dynamic快速解析
string jsonString = "你的目标JSON字符串"; dynamic result = JsonConvert.DeserializeObject(jsonString); // 读取顶层属性 bool success = result.success; int time = result.time; string currency = result.currency; // 遍历动态items foreach (var itemEntry in result.items) { string itemKey = itemEntry.Name; dynamic itemData = itemEntry.Value; string price = itemData.price; double buyOrder = itemData.buy_order; // 其他属性按相同方式读取 }
用JObject实现类型安全的动态解析
string jsonString = "你的目标JSON字符串"; JObject result = JObject.Parse(jsonString); // 读取顶层属性 bool success = (bool)result["success"]; int time = (int)result["time"]; string currency = (string)result["currency"]; // 遍历items JObject items = (JObject)result["items"]; foreach (var kvp in items) { string itemKey = kvp.Key; JToken itemData = kvp.Value; string price = (string)itemData["price"]; double buyOrder = (double)itemData["buy_order"]; // 其他属性按需转换类型读取 }
内容的提问来源于stack exchange,提问作者Александр Панков
相关产品推荐
相关产品推荐

