Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API - How to deserialize a JSON

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; }
}
like image 557
RobinXSI Avatar asked Mar 20 '14 13:03

RobinXSI


2 Answers

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;
like image 66
Loki Avatar answered Nov 17 '22 08:11

Loki


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.

like image 37
Adam Venezia Avatar answered Nov 17 '22 09:11

Adam Venezia