获取JsonConvert结果的第一个元素?

时间:2015-01-11 22:47:19

标签: c# json.net

我在这里使用Riot的API:https://developer.riotgames.com/api/methods#!/909/3144

该请求允许您提供以逗号分隔的用户名列表并返回用户信息。

我正按以下方式执行我的代码:

string getUrl = "https://" + this.regionID + ".api.pvp.net/api/lol/" + this.regionID +
    "/v1.4/summoner/by-name/" + summoner.Text + "?api_key=" + this.apiKey;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    dynamic json = JsonConvert.DeserializeObject<dynamic>(reader.ReadToEnd());
}

返回结果如下:

{
   "prorate": {
      "id": 20335410,
      "name": "ProRate",
      "profileIconId": 693,
      "revisionDate": 1420864656000,
      "summonerLevel": 30
   },
   "jaxelrod": {
      "id": 31034983,
      "name": "Jaxelrod",
      "profileIconId": 744,
      "revisionDate": 1420999923000,
      "summonerLevel": 30
   }
}

现在,假设我想获取列表中返回的第一个用户的ID。我知道我可以使用以下代码执行此操作:

json.prorate.id.ToString();

但是,我不一定知道列表中第一个元素的索引。在这种特定情况下,它是prorate,但每次调用时可能会有所不同。是否有一个调用我可以简单地检索数组的第一个元素?像json.First().id.ToString()

这样的东西

1 个答案:

答案 0 :(得分:1)

您不需要使用动态

var userList  = JsonConvert.DeserializeObject < Dictionary<string, User>>(json);

public class User
{
    public int id { get; set; }
    public string name { get; set; }
    public int profileIconId { get; set; }
    public long revisionDate { get; set; }
    public int summonerLevel { get; set; }
}

您也可以使用Linq

var id = JObject.Parse(json).Children().First().Values<int>("id").First();