Justin Toft
Justin Toft

Reputation: 3

c# Getting the Index from an array inside a JSon Object

I'm trying to find out the index of a string in an array within a JObject object. For example, you could give frc610 and it would return 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.

I've tried multiple different solutions, none of which worked.

Upvotes: 0

Views: 4333

Answers (2)

user1011627
user1011627

Reputation: 1811

Create a class that mimics your data structure, like such (only has 3 of the root fields):

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

Then you can Deserialize the object into a list of those objects and you can use LINQ or other tools to query that list:

        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();

Upvotes: 1

El Duderino
El Duderino

Reputation: 1392

You could just keep the index in variable.

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

Upvotes: 1

Related Questions