-2

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

dbc
  • 104,963
  • 20
  • 228
  • 340
noob_23
  • 137
  • 1
  • 9
  • See https://stackoverflow.com/questions/35206019/using-jsonconvert-deserializeobject-on-nested-object. You'll need to create a class structure starting from the parent object. In order to retrieve just sub-properties without parsing the parent object, you'd need to write a complicated parser to pull out each property by name, which would likely be slower and more difficult than just creating classes for the entire object structure. – Joseph Apr 13 '21 at 03:48
  • @Joseph, thank you for the response. I did look into your initial referenced link and made something like that, but wanted to more specifically look into how parsing the parent object would work. Would you know how to do that in this instance? – noob_23 Apr 13 '21 at 04:08
  • 2
    Please include your JSON as formatted text in your question, not as an image. – ProgrammingLlama Apr 13 '21 at 04:39
  • Will do. Thank you Llama – noob_23 Apr 13 '21 at 04:59
  • https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm – Self Apr 14 '21 at 07:37
  • Does this answer your question? [deserialize part of json string (array) in c#](https://stackoverflow.com/questions/37335030/deserialize-part-of-json-string-array-in-c-sharp) – Self Apr 14 '21 at 07:41

2 Answers2

1

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

(...)
tymtam
  • 31,798
  • 8
  • 86
  • 126
  • Thank you for the response. I prefer your first option and didn't even know that was an option :) – noob_23 Apr 13 '21 at 04:12
1

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

Dharman
  • 30,962
  • 25
  • 85
  • 135