APIMASH: JSON Deserialization for C# Developers – The Undocumented API
Loading...
X

APIMASH: JSON Deserialization for C# Developers

Open Data API’s are a great source of rich , immersive content for building compelling app for Windows.  Part of working with these API’s is handling the dense, super chunky payloads that they return, deserialize them into a usable Data Model that your C# app can use to produce an immersive experience. This article will help you decode the deserialization process step by step so that you can try it for yourself.

APIMASH is the name is a project currently undertaken by Technical Evangelists here at Microsoft to provide a portfolio of starter kits that leverage well known API’s such as TwitterEdmunds, Tumblr and many others in order to inspire you, yes you, to create compelling Windows 8 and Windows Phone apps. Download the APIMASH Starter Kits today and get started.

Open Data API’s are web based services that you invoke by referencing a URL. Instead of returning an HTML page, they return well formed XML or JSON (Javascript Object Notation). For purposes of this discussion I will focus on how to work with JSON.

There are 3 steps we need to take to be able to deserialize a JSON payload.

  1. Document the JSON Payload
  2. Create a set of C# classes that mirror the structure of the JSON Payload
  3. Invoke the API and use a library call to deserialize the JSON string to instantiate the C# classes creating the Data Model

Step 1. Document the JSON Payload

Most API’s provide documentation and in some cases online tools that document the JSON payloads. To see examples of this, I highly recommend that you register at Mashery.com and check out their Mashery API Explorer. Once you are logged into the Mashery portal, navigate to this page:

http://developer.mashery.com/iodocs

image

 

You can use this tool to test Mashery’s API’s and examine the JSON payloads. For example here is the page where you can invoke the Rotten Tomatoes Box Office API and examine the JSON Payload:

image

When you invoke the API, you get a sample JSON payload that you can use to build your Data Model class library

image

If the API you are working with does not provide online documentation, you can get a copy of the JSON payload yourself using a tool like Fiddler.

Step 2. Create the Data Model Class Library

Once you have the JSON payload there are a couple of ways to take that JSON and generate the matching C# classes.

  1. Visual Studio Pro and above provide a ‘Paste Special’ feature that will take JSON or XML and generate C#
  2. The web site JSON2CSharp provides a paste/convert utility

image

Paste the JSON in the tool and click the Generate button. BaZing! C#

public class ReleaseDates
{
    public string theater { get; set; }
    public string dvd { get; set; }
}

public class Ratings
{
    public string critics_rating { get; set; }
    public int critics_score { get; set; }
    public string audience_rating { get; set; }
    public int audience_score { get; set; }
}

public class Posters
{
    public string thumbnail { get; set; }
    public string profile { get; set; }
    public string detailed { get; set; }
    public string original { get; set; }
}

public class AbridgedCast
{
    public string name { get; set; }
    public string id { get; set; }
    public List<string> characters { get; set; }
}

public class AlternateIds
{
    public string imdb { get; set; }
}

public class Links
{
    public string self { get; set; }
    public string alternate { get; set; }
    public string cast { get; set; }
    public string clips { get; set; }
    public string reviews { get; set; }
    public string similar { get; set; }
}

public class Movie
{
    public string id { get; set; }
    public string title { get; set; }
    public int year { get; set; }
    public string mpaa_rating { get; set; }
    public int runtime { get; set; }
    public string critics_consensus { get; set; }
    public ReleaseDates release_dates { get; set; }
    public Ratings ratings { get; set; }
    public string synopsis { get; set; }
    public Posters posters { get; set; }
    public List<AbridgedCast> abridged_cast { get; set; }
    public AlternateIds alternate_ids { get; set; }
    public Links links { get; set; }
}

public class Links2
{
    public string self { get; set; }
    public string alternate { get; set; }
}

public class RootObject
{
    public List<Movie> movies { get; set; }
    public Links2 links { get; set; }
    public string link_template { get; set; }
}

This is a great start but we are not done yet. Next step is to add this code to our solution and then decorate the classes and class members with a few bits of syntactic sugar, the DataContract and DataMember Attributes:

  • DataContract – Specifies that the type defines or implements a data contract and is serializable by a serializer (say that 10 times fast)
  • DataMember – When applied to the member of a type, specifies that the member is part of a data contract and is serializable

You will need to add the DataContract attribute to each class and the DataMember attribute to each member of a class. The DataMember attribute takes an argument that allows you to specify the matching element in the JSON that maps to that data member.

Here is an example of how to apply these attributes to the generated C#:

[DataContract]
public class RottenTomatoesMovies
{
    [DataMember(Name="movies")]
    public List<Movie> movies { get; set; }

    [DataMember(Name="links")]
    public Links2 links { get; set; }

    [DataMember(Name="link_template")]
    public string link_template { get; set; }
}

Step 3. Invoke the API and Deserialize

OK, now that we have grabbed the JSON and used it to generate our C# classes and decorated our classes with the DataContract and DataMember attributes, we are ready to test our creation.

This method invokes the API using the HttpClient object and then calls the method DeserializeObject() to unwind the JSON and instantiate our Data Model:

async public static Task<T> LoadObject<T>(string apiCall)
{
    // instantiate the HTTP client 
    var ws = new HttpClient();

    // take the API string and create a URI object
    var uriAPICall = new Uri(apiCall);

    //make the asynchronous call to retreieve the API response
    var objString = await ws.GetStringAsync(uriAPICall);

    // deserialize the response
    return (T)DeserializeObject<T>(objString);
}

This method is marked async which means that the main thread of the app will not be blocked while we wait for this web service call to return. That is a good thing. The app will remain responsive to the user during this call which could be impacted by network performance.

When the call returns, the JSON payload is contained with a string. Windows provides a built-in API to deserialize JSON to an object model.  Below is the sample code that demonstrates how to invoke this function.

public static T DeserializeObject<T>(string objString)
{
    using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(objString)))
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        return (T)serializer.ReadObject(stream);
    }
}

There is also a popular 3rd party library called JSON.NET that provides JSON deserialization capabilities. I prefer this library in that it provides more advanced error reporting that I found useful during the development process. If there is a bug in your Data Model class type definitions, it will report to you to position within the JSON that failed to deserialize. It helps you debug your C# class structure to make sure it maps directly to the JSON.

JSON.NET can be installed by downloading the library and references the WinRT version of the DLL in your project or through the NUGET installation manager within Visual Studio. Here is a sample of code that demonstrates using JSON.NET:

public static T DeserializeObject<T>(string objString)
{
    return (T)JsonConvert.DeserializeObject<T>(objString, settings);
}

In both cases I have encapsulated the call to these low level library functions in methods that take a generic type parameter <T>. To use these functions you would pass in the type you want to deserialize to.

For example here we invoke the LoadObject() method passing in the type RottenTomatoesMovies type. If the call is successful the JSON response would be deserialized into this type instantiating the apps data model.

var movies = LoadObject<RottenTomatoesMovies>(apiCall);

Conclusion

The APIMASH Starter Kits demonstrate how to create Windows apps that leverage Open Data API’s. They are built using the techniques covered in this article. I recommend you download the APIMASH Starter Kits and dig into the code yourself. Some kits are built in HTML/JS and other in XAML/C# so regardless of your language choice you have great examples of how to get starter with creating a compelling, immersive, fast an fluid mashup app for Windows.

-bob

3 observations on “APIMASH: JSON Deserialization for C# Developers
  1. Jason Williams

    Extraordinarily well done tutorial. I gleaned more from your explanation than a dozen other topics on the subject, including the msdn site, and was able to move on to the next step of my solution. Bravo!

     
    Reply
  2. Pingback: APIMASH Chuck Norris Starter Kit for Windows Phone 8 | BOB FAMILIAR

  3. Pingback: APIMASH Chuck Norris Starter Kit | bob familiar

Leave Your Observation

Your email address will not be published. Required fields are marked *

Read previous post:
APIMASH: The Edmunds API Starter Kit

The APIMASH Edmunds StarterKit is a XAML/C# Windows 8 app based on the default Blank Template that demonstrates calling the...

Close