-1

Currently I am using C# like so to access a particular endpoint from a sports statistics API

class GetPlayerData
{
    public string retrievePlayerStats()
    {
        var URL = new UriBuilder("https://statsapi.web.nhl.com/api/v1/people/8471698/stats?stats=statsSingleSeason&season=20202021");

        var client = new WebClient();

        dynamic PlayerData = JObject.Parse(client.DownloadString(URL.ToString()));

        string PlayerStats = PlayerData.stats.ToString();

        return PlayerStats;
    }
}

The call works with no issue returning the following result seen formatted at the link below:

https://statsapi.web.nhl.com/api/v1/people/8471698/stats?stats=statsSingleSeason&season=20202021

My question is how do I access the items in the sub-array "splits". I want to be able to bring back a single stat for the player like goals or time on ice. If I try the commented options below I receive an error that says "Cannot perform runtime binding on a null reference". I am fairly new to C# so hopefully the answer is easy and any help (or even other options completely) on how to do this is much appreciated.

public string retrievePlayerStats()
{
    var URL = new UriBuilder("https://statsapi.web.nhl.com/api/v1/people/8471698/stats?stats=statsSingleSeason&season=20202021");

    var client = new WebClient();

    dynamic PlayerData = JObject.Parse(client.DownloadString(URL.ToString()));

    string PlayerName = PlayerData.stats.ToString();
    //string PlayerName = PlayerData.splits.ToString(); --null reference error
    //string PlayerName = PlayerData.stats.splits.ToString(); --null reference error

    return PlayerName;
}

Thank you!

Just Shadow
  • 10,860
  • 6
  • 57
  • 75
Gazrok
  • 99
  • 2
  • 8
  • Does this answer your question? [How to auto-generate a C# class file from a JSON string](https://stackoverflow.com/questions/21611674/how-to-auto-generate-a-c-sharp-class-file-from-a-json-string) – Drag and Drop Feb 18 '21 at 14:44

1 Answers1

2

Instead of dynamic-s you can use JObject-s and JArray-s like this:

JObject PlayerData = JObject.Parse(client.DownloadString(URL.ToString()));

var stats = PlayerData["stats"] as JArray;

foreach (JObject stat in stats)
{
    var splits = stat["splits"] as JArray;
    foreach (JObject split in splits)
    {
        var splitStat = split["stat"] as JObject;
        // Now you have access to the "stat"
        // Do whatever you want
        // Here is a sample for accessing the goals 
        var goals = splitStat["goals"].ToString();
        Console.WriteLine(goals);
    }
}

Here's a sample: https://dotnetfiddle.net/6uKPYf

P.S. In general I would create a class, do proper deserializations and work on the classes, but the solution above should fix your problem.

Just Shadow
  • 10,860
  • 6
  • 57
  • 75