C# 使用JObject从JSON检索数据
我试图从JSON中获取游戏的值,但有多个字段具有相同的名称,因此我想知道是否有一种方法可以检索单个值,以下是基本的JSON结构:C# 使用JObject从JSON检索数据,c#,json,json.net,C#,Json,Json.net,我试图从JSON中获取游戏的值,但有多个字段具有相同的名称,因此我想知道是否有一种方法可以检索单个值,以下是基本的JSON结构: "response": { "game_count": 119, "games": [ { "appid": 3920, "playtime_forever": 0 }, { "appid": 4000, "
"response": {
"game_count": 119,
"games": [
{
"appid": 3920,
"playtime_forever": 0
},
{
"appid": 4000,
"playtime_forever": 278
},
我需要通过使用appID,然后检索
playtime\u forever
键来获取属性。您可以将JSON转换为类,然后查询:
class ResponseJSON
{
[JsonProperty("response")]
public Result Response { get; set; }
}
class Result
{
[JsonProperty("game_count")]
public string Count { get; set; }
[JsonProperty("games")]
public List<Game> Gmaes { get; set; }
}
class Game
{
[JsonProperty("appid")]
public string Id { get; set; }
[JsonProperty("playtime_forever")]
public string PlayTime { get; set; }
}
var resp = JsonConvert.DeserializeObject<ResponseJSON>(jsonstr);
或者您可以使用linq查询您的游戏:
var selectiveGames = resp.Response.Games.Where(x=> x.PlayTime == 220).ToList();
如果没有newtonsoft dll,则需要将其从添加到项目中
更新:使用原始JSON,上面的代码工作得非常完美。我已经这样做了,它只是说
对象引用未设置为对象的实例。
在foreach循环上检查更新@John我刚刚用我的控制台应用程序测试了你的JSON,它几乎在那里工作,我刚刚在response.response.Games.Where
:CommandRegistry.Result不包含游戏定义anyidea@Yasser@Yasser没有必要回答,只是让代码不起作用
var selectiveGames = resp.Response.Games.Where(x=> x.PlayTime == 220).ToList();