Sunday, March 2, 2014

Working with JSON and HTTP requests

In this post I'm gonna demonstrate how to working with HTTP requests and JSON in Windows Phone and Windows store Applications.

I'm demonstrating Windows Phone App here, there is no different withe method if you are in the Windows Store app either.

1. Create new Windows phone App. I'm using default Windows Phone Data bound App template here.


2. Then Go to the ViewModels -> MainViewModel in the Solution Explorer and find the
  public void LoadData()
and clear all codes in it.

3. 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

4. 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. I'll post later abut Nugets

5. Then change LoadData() as async
  public async void LoadData()  

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");


6. 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

PM> Install-Package Newtonsoft.Json

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

7. 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  I changed RootObject to songRoot

8. Here is the code part for de-serializing


songRoot deserialized = await JsonConvert.DeserializeObjectAsync<songRoot>(jsonResponse);


9. We are done.. 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;
}


Enjoy





Full Code In Media Fire 
http://bit.ly/NJqpAb



1 comments:

Shankar said...

Thanks a lot. Was really helpful