C#中将多个JSON对象反序列化为List的问题求助
Hey there, let's sort out that deserialization error you're facing! The core issue here is a mismatch between your JSON structure and the type you're trying to deserialize into.
问题根源
Looking at the JSON sample you provided, the structure is a dictionary where each key is an item ID (string format), and the value is a single ItemSummary object — not a list of them. Your original code tried to deserialize into Dictionary<string, List<ItemSummary>>, which expects each key to map to an array of items, hence the error about expecting a JSON array.
修正后的反序列化代码
First, we need to deserialize into the correct type: Dictionary<string, ItemSummary>. Then, since the item ID is stored as the dictionary key (and not included in the inner JSON object), we'll need to manually assign that ID to each ItemSummary instance before converting to a list.
Here's the fixed getitemsummary method:
public List<ItemSummary> getitemsummary() { string rawjson = getitemsummaryraw(); if (rawjson != null) { // 反序列化为键是物品ID字符串、值是ItemSummary的字典 var itemDictionary = JsonConvert.DeserializeObject<Dictionary<string, ItemSummary>>(rawjson); // 遍历字典,将键(物品ID)赋值给对应的ItemSummary的id属性,再转为列表 var itemList = itemDictionary.Select(entry => { entry.Value.id = int.Parse(entry.Key); return entry.Value; }).ToList(); return itemList; } else { return null; } }
额外优化(资源泄漏防护)
Your getitemsummaryraw method can be improved by wrapping disposable objects in using statements to ensure resources are properly released:
public string getitemsummaryraw() { var apisource = "https://rsbuddy.com/exchange/summary.json"; try { using (var webreq = WebRequest.Create(apisource)) using (var webres = webreq.GetResponse()) using (var webstream = webres.GetResponseStream()) using (var sr = new StreamReader(webstream)) { return sr.ReadToEnd(); } } catch (WebException e) { Console.WriteLine(e); return null; } }
验证逻辑
After making these changes, you'll end up with a List<ItemSummary> where each item has its correct id populated, ready for you to use in your subsequent API calls for item details.
内容的提问来源于stack exchange,提问作者Matthew Arnold

