I am trying to consume an API.
I want to store following Request in an Object: http://api.swissunihockey.ch/rest/v1.0/clubs/655
The Problem is, that the Object is initialized but all the values are null.
I can receive the data and generate an output as a string. But the De-serialization to the Object doesn't work. Can you help?
private static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://api.swissunihockey.ch/rest/v1.0/clubs/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = await client.GetAsync("615");
var club = await response.Content.ReadAsAsync<Club>();
Console.WriteLine(club.Name);
Console.Read();
}
catch (HttpRequestException e)
{
if (e.Source != null)
{
Console.WriteLine("HttpRequestException source: {0}", e.Source);
}
}
}
}
This is the Club class I am trying to store the data:
class Club
{
public int Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string Zip { get; set; }
public string City { get; set; }
public string Canton { get; set; }
public string Phone { get; set; }
public string Url { get; set; }
}
You need another class containing Club which will be deserialized further.
class Response
{
public Club Club { get; set; }
}
Then deserialize as
var res = await response.Content.ReadAsAsync<Response>();
var club = res.Club;
Once you have the string from the response, use the package that Web API already references from Nuget, Json.Net by Newtonsoft.Json1, and call Club c = JsonConvert.Deserialize<Club>(responseString);
I find this to be far simpler than the built in Data Contracts already mentioned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With