Search code examples
c#json.netjsonconvert

Using JsonConvert.DeserializeObject() Method for nested attributes in c#


I have the following JSON file and was hoping someone could tell me how to simply access the nested "player_status" and "previous_teams" values using the JsonConvert.DeserializeObject() Method. Any references tot tutorials better than the outdated sites I have seen would be helpful too. enter image description here

Thank you


Solution

  • Option 1 is to parse or query json. please see the official Querying JSON with LINQ or Querying JSON with SelectToken for Json.NET or JsonDocument.Parse for the new System.Text.Json serialiser.

    If you want/need to use JsonConvert.DeserializeObject then you will need to create a set of classes that represents your data.

    public class League 
    {
       public List<Team> Details { get; set;} 
    }
    public class Team 
    {
     public List<AboutPlayers> Players {get; set;}
    }
    
    public class AboutPlayers 
    {
     public List<Capatin> Captains {get; set;}
    }
    
    public class Captain 
    {
     public string Player_Status{get; set;}
     public PlayerHistory Player_History {get; set;}
    }
    
    (...)