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

161 Views Asked by At

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

2

There are 2 best solutions below

1
On BEST ANSWER

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

(...)
0
On

You can use JSON Path to query it. See: https://www.newtonsoft.com/json/help/html/QueryJsonSelectToken.htm

    JObject json = JObject.Parse("{ json string }");
    var playerStatus = json.SelectToken("details[0].players.captains[0].player_status");
    var previousTeams = json.SelectToken("details[0].players.captains[0].player_history.previous_teams");