this is a basic web api call using HttpClient
and parse some part of the result, this was working as expected, but the part inside the if (response.IsSuccessStatusCode)
doesnt seems right. It feels like it can be simplified, but I don't know how.
static async Task<List<Hero>> GetHero(string url, string urlParameters)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var response = client.GetAsync(urlParameters).Result)
{
if (response.IsSuccessStatusCode)
{
var heroes = new List<Hero>();
var jsonResult = await response.Content.ReadAsStringAsync();
var deserializedjsonResult = JObject.Parse(jsonResult);
var resultHeroes = deserializedjsonResult["result"]["heroes"].ToList();
resultHeroes.ForEach(x => heroes.Add(x.ToObject<Hero>()));
return heroes;
}
}
return null;
}
the api that I was calling will return something in this format
{
"result": {
"heroes": [
{
...
},
{
...
}
],
"villains": [
{
...
},
{
...
}
],
"extras": [
{
...
},
{
...
}
],
}
}