More Json With Windows Phone

Tags: windows phone, JSON, REST, Services

A few weeks ago, I did a short blog post on consuming Json from Windows Phone. I posted more as a reference for myself but I have gotten a few emails about it so I figured I would expand on it. Consuming Json is Windows Phone is not hard but it can be a bit trick. The problem is on the parsing. Unlike XML, there is no LinqToJson available to allow us to parse / query Json. The best way to parse it is to Deserialize the message to a know type.

That is he issues. Some types the services we need to communicate can be somewhat complex. No that is would be difficult to create a type for the message but I can be very tedious and error prone.

To make things easier, I found a great Json class generator.

image

You basically paste in some Json, and it generates a set of classes you can use to parse it.

Now is you look the Json I pasted, you will notice that is it not very well formatted. The generator will work either way but sometimes you might need to debug the Json and it would be a nightmare to debugged it with that formatting. To help I use this great tool. 

image

The Json class generator uses the Newtonsoft.Json library for Windows Phone. Best way to get it installed is to use NuGet:

image

So, the code would look like this:

public ObservableCollection<SpeakerItemModel> GetSpeakers()
{
    SpeakerList = new ObservableCollection<SpeakerItemModel>();
    WebClient wc = new WebClient();
    wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(SpeakerCompleted);
    wc.DownloadStringAsync(new Uri(Settings.SpeakerServiceUri));
    return SpeakerList;   
}

void SpeakerCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    //needed to append {"Speakers": and add } to the end to property format the json 
    string SpeakerJson = string.Format(@"{{ ""Speakers"":{0}}}", e.Result);
    SpeakerResponse response = new SpeakerResponse(SpeakerJson);

    for (int i = 0; i < response.Speakers.Length; i++)
    {
        SpeakerList.Add(new SpeakerItemModel
        {
            Bio = response.Speakers[i].Bio,
            FirstName = response.Speakers[i].FirstName,
            Id = response.Speakers[i].Id,
            LastName = response.Speakers[i].LastName,
            PictureUrl = response.Speakers[i].PictureUrl,
            Position = response.Speakers[i].Position,
            Twitter = response.Speakers[i].Twitter
        });

    }
}

 

Add a Comment