Working with HTTP and JSON

This article is about how to work with HTTP requests and JSON in Windows Phone and Windows store Applications.

The sample is a Windows Phone App, but the same methods would apply for a Windows Store app.

What is JSON ?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. (Reference - http://json.org/)

Working On Codes

  1. Create new Windows phone App. I'm using default Windows Phone Data bound App template here.
    http://1.bp.blogspot.com/-DtpkDFQ7BB4/UxM7U5qZD1I/AAAAAAAAAi4/H-V68Rv4f5E/s1600/Untitled.png

  2. Then Go to the ViewModels -> MainViewModel in the Solution Explorer and find the

public void  LoadData()

and clear all codes in it.

  1. We are going to use iTune search Service.. Here is the Http GET url for it. You can try it with your browser too
    http://itunes.apple.com/search?term=metallica

  2. To handle Http Requests we need to install additional Nuget Package in to the project.
    Tools -> Nuget Package Manager -> Package Manager Console
    In the console then type

Install-Package Microsoft.Net.Http

Then Press enter.. You need internet connection to install it.

  1. Then change LoadData() as async
    for get the response from the Service use following code
public async void LoadData()
        {
            // Sample data; replace with real data
            //this.Items.Add(new ItemViewModel() { ID = "0", LineOne = "runtime one", LineTwo = "Maecenas praesent accumsan bibendum", LineThree = "Facilisi faucibus habitant inceptos interdum lobortis nascetur pharetra placerat pulvinar sagittis senectus sociosqu" });
 
            HttpClient client = new  HttpClient();
 
            string jsonResponse = await client.GetStringAsync("http://itunes.apple.com/search?term=metallica");
  1. Response cumming as a string we need to convert it to Objects , it will helpful to manage it
    for that install Newtonsoft.Json Package in Nuget Package Manager as same as Microsoft.Net.Http
    **
    **Install-Package Newtonsoft.Json

****then de-serialize the string in to code... we need classes to convert this string to objects.

  1. For that, get the Json response string . (Put break point below this line)
string jsonResponse = await client.GetStringAsync("http://itunes.apple.com/search?term=metallica");

Copy it and

go to the http://json2csharp.com/
paste and click on Generate It will give You class set that you need to de-serialize Json
Add those classes to the namespace  change RootObject to songRoot

  1. Here is the code part for de-serializing
    ** **
songRoot deserialized = await JsonConvert.DeserializeObjectAsync<songRoot>(jsonResponse);
  1. Then bind the data as  you want.. Here is my total code in LoadData(). None of other codes are change.
public async void LoadData()
        {
             
            HttpClient client = new  HttpClient();
 
            string jsonResponse = await client.GetStringAsync("http://itunes.apple.com/search?term=metallica");
 
            //for deserialize json and get the class
            songRoot deserialized = await JsonConvert.DeserializeObjectAsync<songRoot>(jsonResponse);
 
            foreach (var item in deserialized.results)
            {
                this.Items.Add(new ItemViewModel()
                {
                    ID = item.trackId.ToString(),
                    LineOne = item.trackName,
                    LineTwo = item.trackPrice.ToString(),
                    LineThree = item.trackCount.ToString(),
                });
            }
 
            this.IsDataLoaded = true;
        }

Here is the screen shot
http://1.bp.blogspot.com/-hMdRDWIFLAs/UxNrrYU0PtI/AAAAAAAAAjI/C2RxQOOACuI/s1600/wp_ss_20140302_0001.png
Download full code : http://bit.ly/NJqpAb