Reputation: 3247
I'm sure the answer to this is extremely simple but I'm having trouble. I have the following JSON string (provided by the Yahoo Fantasy Sports API) that I'm trying to parse into my model objects from a JSON.NET JToken. Because I do not want to litter my project with a bunch of classes specifically to support JSON parsing, I'm trying to do this manually. However, I cannot for my life figure out in the code how to determine whether I'm in the settings case or the teams case. Help?
{
"league":[
{
"league_key":"somevalue",
"name":"My League"
},
{
"teams":{
"0":{
"team":[
[
// some data
]
]
},
"1":{
"team":[
[
// some data
]
]
},
"count":2
}
}
]
}
The following is the code I'm using for parsing (so far):
public League ParseJson(JToken token)
{
var league = new League();
if (token.Type == JTokenType.Array)
{
foreach (var child in token.Children<JObject>())
{
// how do I figure out if this child contains the settings or the teams?
}
return league;
}
return null;
}
I don't want to hardcode it because I might load more/different subresources from a league so it's not guaranteed that it will always contain this structure.
Upvotes: 0
Views: 1222
Reputation: 129827
Just check whether the child object contains a known property from the subresource you want (which isn't also in one of the other subresources). Something like this should work. You can fill in the rest.
public League ParseJson(JToken token)
{
var league = new League();
if (token.Type == JTokenType.Array)
{
foreach (JObject child in token.Children<JObject>())
{
if (child["teams"] != null)
{
// process teams...
foreach (JProperty prop in child["teams"].Value<JObject>().Properties())
{
int index;
if (int.TryParse(prop.Name, out index))
{
Team team = new Team();
JToken teamData = prop.Value;
// (get team data from JToken here and put in team object)
league.Teams.Add(team);
}
}
}
else if (child["league_key"] != null)
{
league.Key = child["league_key"].Value<string>();
league.Name = child["name"].Value<string>();
// (add other metadata to league object here)
}
}
return league;
}
return null;
}
class League
{
public League()
{
Teams = new List<Team>();
}
public string Key { get; set; }
public string Name { get; set; }
public List<Team> Teams { get; set; }
}
class Team
{
// ...
}
Upvotes: 1