2017-04-24 143 views
0

我试图找出一个JObject对象内的数组中的字符串的索引。例如,你可以给frc610,它会返回0.c#从一个JSon对象内的数组获取索引

// 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

我已经尝试了多种不同的解决方案,其中没有一个工作。

回答

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); 
+0

谢谢,作品像一个魅力! –

1

创建模仿你的数据结构,就像一类这样的(只有根域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(); 
+0

我相信这个方法也可以运行,效率可能更高,但另一个@ Austin更容易添加到我的代码中。 –