2017-04-22 87 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