【问题标题】:c# Getting the Index from an array inside a JSon Objectc# 从 JSon 对象内的数组中获取索引
【发布时间】:2017-04-24 00:21:44
【问题描述】:

我正在尝试在 JObject 对象的数组中找出字符串的索引。例如,你可以给 frc610,它会返回 0。

// Get rankings JSON file from thebluealliance.com 
        string TBArankings = @"https://www.thebluealliance.com/api/v2/district/ont/2017/rankings?X-TBA-App-Id=frc2706:ONT-ranking-system:v01";
        var rankings = new WebClient().DownloadString(TBArankings);

        string usableTeamNumber = "frc" + teamNumberString;
        string team_key = "";
        int rank = 0;

        dynamic arr = JsonConvert.DeserializeObject(rankings);
        foreach (dynamic obj in arr)
        {
            team_key = obj.team_key;
            rank = obj.rank;
        }

        int index = Array.IndexOf(arr, (string)usableTeamNumber);  // <-- This is where the exception is thrown.

        Console.WriteLine(index);

        // Wait 20 seconds
        System.Threading.Thread.Sleep(20000);

Here's the json file I'm using

我尝试了多种不同的解决方案,但都没有奏效。

【问题讨论】:

    标签: c# arrays json json.net


    【解决方案1】:

    您可以将索引保持在变量中。

        string usableTeamNumber = $"frc{teamNumberString}";
        string team_key = "";
        int rank = 0;
        int index = 0;
        int count = 0;
    
        dynamic arr = JsonConvert.DeserializeObject(rankings);
        foreach (dynamic obj in arr)
        {
            team_key = obj.team_key;
            rank = obj.rank;
    
            if (usableTeamNumber.Equals(team_key) {
                 index = count;
            }
    
            count++;
        }
    
        Console.WriteLine(index);
    

    【讨论】:

      【解决方案2】:

      创建一个模仿你的数据结构的类,像这样(只有 3 个根字段):

      public class EventPoints
      {
          public int point_total { get; set; }
          public int rank { get; set; }
          public string team_key { get; set; }
      }
      

      然后您可以将对象反序列化为这些对象的列表,然后您可以使用 LINQ 或其他工具来查询该列表:

              string teamNumberString = "frc2056";
              string TBArankings = @"https://www.thebluealliance.com/api/v2/district/ont/2017/rankings?X-TBA-App-Id=frc2706:ONT-ranking-system:v01";
              var rankings = new WebClient().DownloadString(TBArankings);
      
              List<EventPoints> eps = JsonConvert.DeserializeObject<List<EventPoints>>(rankings);
      
              EventPoints sp = eps.Where(x => x.team_key.Equals(teamNumberString)).FirstOrDefault();
      
              Console.WriteLine(eps.IndexOf(sp));
      
              Console.ReadLine();
      

      【讨论】:

      • 我相信这也可以,并且可能更有效,但其他 @Austin 更容易添加到我的代码中。
      猜你喜欢
      • 1970-01-01
      • 2020-05-04
      • 2012-12-31
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      相关资源
      最近更新 更多