首页 > 解决方案 > 如何反序列化没有键的json数组?C#

问题描述

我正在为 riot games api 开发一个 api 包装器。我遇到了以下端点的问题:

Champion-mastery/v4/champion-masteries/by-summoner/{encryptedSummonerId}

我正在使用 newtonsoft json 和 RestSharp 来获得结果。这是我的代码。

public Masteries getMasteriesBySummoner(string id, string server)
{
    RestClient client = new RestClient($"https://{getServer(server)}.api.riotgames.com/lol/");
    RestRequest request = new RestRequest($"champion-mastery/v4/champion-masteries/by-summoner/{id}");
    request.AddHeader("X-Riot-Token", key);

    var response = client.Get(request);
    Masteries masteries = JsonConvert.DeserializeObject<Masteries>(response.Content);
    return masteries;
}

这种模式适用于大约 80% 的端点。然而,对于这个特定的端点,会返回一个 JSON 数组。这个特定的 json 数组也没有像所有其他数组一样的键,例如“数据”或“条目”。所以我似乎无法弄清楚如何正确制作掌握模型。这是我到目前为止所拥有的

public class Masteries
{
    public int championLevel { get; set; }
    public bool chestGranted { get; set; }
    public int championPoints { get; set; }
    public int championPointsSinceLastLevel { get; set; }
    public int championPointsUntilNextLevel { get; set; }
    public string summonerId { get; set; }
    public int tokensEarned { get; set; }
    public int championId { get; set; }
    public object lastPlayTime { get; set; }
}

它适用于一个条目,但不适用于整个数组。添加列表似乎不起作用,因为没有键可以作为列表的基础。

这是 JSON 模式的示例...

[
    {
        "championLevel": 7,
        "chestGranted": false,
        "championPoints": 70594,
        "championPointsSinceLastLevel": 48994,
        "championPointsUntilNextLevel": 0,
        "summonerId": "xaZh_7U2VIRtArKG-mgda_Rt9TSRVRmhBp2GFE88bmTSqJU",
        "tokensEarned": 0,
        "championId": 10,
        "lastPlayTime": 1537676432000
    },
    {
        "championLevel": 7,
        "chestGranted": true,
        "championPoints": 51273,
        "championPointsSinceLastLevel": 29673,
        "championPointsUntilNextLevel": 0,
        "summonerId": "xaZh_7U2VIRtArKG-mgda_Rt9TSRVRmhBp2GFE88bmTSqJU",
        "tokensEarned": 0,
        "championId": 69,
        "lastPlayTime": 1548208513000
    }
]

任何帮助表示赞赏,谢谢。

标签: c#jsonjson.netriot-games-api

解决方案


推荐阅读