C# 在JSON中访问子值

C# 在JSON中访问子值,c#,json,parsing,C#,Json,Parsing,如何访问第一个项目id using (var http = new HttpClient()) { var res = JArray.Parse(await http.GetStringAsync("http://api.champion.gg/champion/Gragas?api_key=????").ConfigureAwait(false)); ^^^^^^ // Also tried with JObject inst

如何访问第一个项目id

    using (var http = new HttpClient())
    {
        var res = JArray.Parse(await http.GetStringAsync("http://api.champion.gg/champion/Gragas?api_key=????").ConfigureAwait(false));
                  ^^^^^^ // Also tried with JObject instead of JArray, both don't work
        var champion = (Uri.EscapeUriString(res[0]["items"][0]["mostGames"][0]["items"][0]["id"].ToString()));
        Console.WriteLine(champion);        //  ^ [0] here because the JSON starts with an [
    } 
示例JSON结果(由于原始JSON超过21500个字符,因此使其更小,确保其有效,以下是原始JSON响应:)

使用JArray时,我出现以下错误:
访问的JObject值的键值无效:0。需要对象属性名称。

对于JObject,我得到以下错误:
从JsonReader读取JObject时出错。当前JsonReader项不是对象:StartArray。路径“”,第1行,位置1。

提前谢谢,我希望我能解释清楚

应该是:

var champion = (Uri.EscapeUriString(res[0]["items"]["mostGames"]["items"][0]["id"].ToString()));
最外层的
“items”
属性的值是单个对象,而不是数组,因此
[“items”][0]
中不需要
[0]
。类似地,
“mostGames”
具有单个对象值,因此在
[“mostGames”][0]
中不需要
[0]

样品

请注意,如果
“items”
有时是对象数组,但有时是单个对象而不是一个对象数组,则可以引入以下扩展方法:

public static class JsonExtensions
{
    public static IEnumerable<JToken> AsArray(this JToken item)
    {
        if (item is JArray)
            return (JArray)item;
        return new[] { item };
    }
}
应该是:

var champion = (Uri.EscapeUriString(res[0]["items"]["mostGames"]["items"][0]["id"].ToString()));
最外层的
“items”
属性的值是单个对象,而不是数组,因此
[“items”][0]
中不需要
[0]
。类似地,
“mostGames”
具有单个对象值,因此在
[“mostGames”][0]
中不需要
[0]

样品

请注意,如果
“items”
有时是对象数组,但有时是单个对象而不是一个对象数组,则可以引入以下扩展方法:

public static class JsonExtensions
{
    public static IEnumerable<JToken> AsArray(this JToken item)
    {
        if (item is JArray)
            return (JArray)item;
        return new[] { item };
    }
}

你是真正的上帝你是真正的上帝