使用JObject从JSON检索数据

时间:2017-01-29 21:10:15

标签: c# json json.net

我试图从JSON获取游戏的值,但是有多个字段具有相同的名称,所以我想知道是否有一种方法可以检索该单个值,这里是基本的JSON结构:

"response": {

    "game_count": 119,
    "games": [
        {
            "appid": 3920,
            "playtime_forever": 0
        },
        {
            "appid": 4000,
            "playtime_forever": 278
        },

...

我需要以某种方式使用appID获取属性,然后检索playtime_forever密钥。

1 个答案:

答案 0 :(得分:3)

您可以将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);

然后你可以使用for循环迭代你的对象:

foreach(game in resp.Respone.Games) {
   var playtime = game.PlayTime;
  // do stuff here
}

或者您可以使用linq查询您的游戏:

var selectiveGames = resp.Response.Games.Where(x=> x.PlayTime == 220).ToList();

如果您没有,可以将here中的newtonsoft dll添加到您的项目中;

更新:使用原始JSON,上面的代码工作正常。