2017-04-22 27 views
1

我如何访问第一个项目ID?在JSON中获取子值

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字,确信它适用于有https://jsonlint.com,原来这里是JSON响应:https://hastebin.com/sacikozano.json

[{ 
    "key": "Gragas", 
    "role": "Jungle", 
    "overallPosition": { 
     "change": 1, 
     "position": 13 
    }, 
    "items": { 
     "mostGames": { 
      "items": [{ 
        "id": 1402, 
        "name": "Enchantment: Runic Echoes" 
       }, 
       { 
        "id": 3158, 
        "name": "Ionian Boots of Lucidity" 
       }, 
       { 
        "id": 3025, 
        "name": "Iceborn Gauntlet" 
       }, 
       { 
        "id": 3065, 
        "name": "Spirit Visage" 
       }, 
       { 
        "id": 3742, 
        "name": "Dead Man's Plate" 
       }, 
       { 
        "id": 3026, 
        "name": "Guardian Angel" 
       } 
      ], 
      "winPercent": 50.45, 
      "games": 300 
     } 
    } 
}] 

随着JArray我得到以下错误:Accessed JObject values with invalid key value: 0. Object property name expected.

随着JObject我得到以下错误:Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.

由于提前,我希望我解释它很好

回答

0

它应该是:

var champion = (Uri.EscapeUriString(res[0]["items"]["mostGames"]["items"][0]["id"].ToString())); 

最外面"items"属性有一个单一的对象作为其值,而不是一个数组,所以不需要在["items"][0][0]。同样,"mostGames"具有单个对象值,所以在["mostGames"][0]中不需要[0]

样品fiddle

注意,如果"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"].AsArray().First()["mostGames"]["items"][0]["id"].ToString())); 
+0

U是真神 – hehexd