以JSON

时间:2017-04-22 21:59:54

标签: 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 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.

提前致谢,我希望我解释得很好

1 个答案:

答案 0 :(得分:0)

应该是:

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

最外面的"items"属性有一个对象作为其值,而不是数组,因此[0]中不需要["items"][0]。同样,"mostGames"只有一个对象值,因此[0]中不需要["mostGames"][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()));