0

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.

0

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I'm sure this works as well and is likely more efficient but the other @Austin's was easier to add to my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.