c# - C# 中的 JSON:如何获取某个类下的 json 字符串中的所有对象?
问题描述
我正在尝试将所有内容放在应用程序下方并将值放入Dictionary<string, Games>
我正在使用下面的代码。
班级:
public class Games
{
public int AppId { get; set; }
public string Name { get; set; }
}
代码:
public Dictionary<string, Games> GetAllGames()
{
//http://api.steampowered.com/ISteamApps/GetAppList/v0002/?key=STEAMKEY&format=json
var url = "http://api.steampowered.com/ISteamApps/GetAppList/v0002/?key=STEAMKEY&format=json";
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(url));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
string jsonString;
using (Stream stream = WebResp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
var t = JObject.Parse(jsonString).SelectToken("applist").ToString();
var s = JObject.Parse(t).SelectToken("apps").ToString();
Dictionary<string, Games> gamesList = JsonConvert.DeserializeObject<Dictionary<string, Games>>(s);
return gamesList;
}
错误:
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,LudumPricer.Games]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
JSON 示例:
{
"applist":{
"apps":[
{
"appid":5,
"name":"Dedicated Server"
},
{
"appid":7,
"name":"Steam Client"
},
{
"appid":8,
"name":"winui2"
},
{
"appid":10,
"name":"Counter-Strike"
}
]
}
}
我想获取apps
属性下的所有内容并将它们放入Dictionary <string, Games>
我正在使用 newtonsoft json.net 库
解决方案
只需转换和使用ToDictionary
给定
public class App
{
public int appid { get; set; }
public string name { get; set; }
}
public class Applist
{
public List<App> apps { get; set; }
}
public class RootObject
{
public Applist applist { get; set; }
}
用法
var root = JsonConvert.DeserializeObject<RootObject>(jsonString);
var dict = root.applist.apps.ToDictionary(x => x.appid, x => x.name);
Enumerable.ToDictionary 方法(IEnumerable、Func)
根据指定的键选择器函数从 IEnumerable 创建字典。
推荐阅读
- python - 如何洗牌 ndarray 中的所有元素,每种方法之间有什么区别?
- reactjs - 我可以使用 React.js MapBox GL JS 获取在 MapBox Studio 中创建的 MapBox 图层吗?
- html - 旋转元素的绝对定位到左上角
- math - 几何平移是线性的吗?
- android - 横向布局,无旋转
- python - 使用 curl 登录 phpBB
- swiftui - xcode swift .navigationBarItems 按钮如何在中间对齐并与顶部有一些间距
- popup - Mediawiki:安装弹出窗口扩展
- c# - 如何在棋盘上创建曲线(统一的立方体),角色在哪里可以选择走或不走另一条路?基于骰子的运动
- macos - 我需要一些使用 Mac 终端安装或创建应用程序