Reputation: 41
I am trying to deserialize the following data and display them using C#:
{
"_links":{
"self":{
"href":"http://api.football-data.org/v1/competitions/426/teams"
},
"competition":{
"href":"http://api.football-data.org/v1/competitions/426"
}
},
"count":"20",
"teams":[
{
"_links":{
"self":{
"href":"http://api.football-data.org/v1/teams/322"
},
"fixtures":{
"href":"http://api.football-data.org/v1/teams/322/fixtures"
},
"players":{
"href":"http://api.football-data.org/v1/teams/322/players"
}
},
"name":"Hull City FC",
"code":"HUL",
"shortName":"Hull",
"squadMarketValue":"122,250,000 €",
"crestUrl":"http://upload.wikimedia.org/wikipedia/de/a/a9/Hull_City_AFC.svg"
},
{
"_links":{
"self":{
"href":"http://api.football-data.org/v1/teams/338"
},
"fixtures":{
"href":"http://api.football-data.org/v1/teams/338/fixtures"
},
"players":{
"href":"http://api.football-data.org/v1/teams/338/players"
}
},
"name":"Leicester City FC",
"code":"LCFC",
"shortName":"Foxes",
"squadMarketValue":"205,300,000 €",
"crestUrl":"http://upload.wikimedia.org/wikipedia/en/6/63/Leicester02.png"
}
]
}
I have generated these classes:
public class Team
{
public Links2 _links { get; set; }
public string name { get; set; }
public string code { get; set; }
public string shortName { get; set; }
public string squadMarketValue { get; set; }
public string crestUrl { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public int count { get; set; }
public List<Team> teams { get; set; }
}
I then tried to parse and display the data:
private void ParseAndDisplay(JsonValue json)
{
dynamic jsonObj = JsonConvert.DeserializeObject(json);
foreach (var obj in jsonObj.teams)
{
Console.Out.WriteLine(obj.name);
}
}
However it seems to break when entering the foreach loop. Can anyone tell me what I am missing or doing wrong? An unhandled exception error appears.
Upvotes: 1
Views: 1876
Reputation:
Your code is correct only, unless you update your question with the error.
Okay, let me tell you one more way to do it in .net. You can also use Linq
Newtonsoft.Json.Linq
to your project.And add the following code
dynamic jsonObj = JObject.Parse(your_JSON_string);
foreach (var obj in jsonObj.teams)
{
Console.WriteLine(obj.name);
}
Upvotes: 0
Reputation: 742
To extract the team names from your list of teams you have to query the list.
RootObject jsonObj = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var obj in jsonObj.teams.Select(x => x.name))
{
Console.Out.WriteLine(obj);
}
Upvotes: 1