Parsing JSON in Windows Phone

Today we will discuss how to call an Application Programming Interface (API) in Windows Phone for the JSON format.

The JSON format is not officially supported in Windows Phone so we have to use a third party DLL to parse the JSON.

For that purpose we have to use NewtonSoft's DLL to deserialize the JSON Object.

It can be downloaded from here.

Quest 1: Find an API of JSON format, that may be any of the APIs.

To search for the API I recommend you: 
 
http://www.programmableweb.com/

This will help you very much to find an API.

Quest 2: After you have found an API you need to validate the API, to do that you can use the following link: JSONLint.

Quest 3: For a specific type of API you need to make reference classes so you may desrialize the object casting the very class.
 
For this quest we have another online solution for you that generates the classes for you, they are: http://json2csharp.com/.

You just put your API link here and it will automatically generate the classes for you.

Programming Quest 1:

After downloading the NewtonSoft's DLL you would need to reference the DLL in your project.

Go to Refrences, Add new Reference then Browse for the specific DLL.
 
Programming Quest 2:

You would have to add classes to the project so you may cast the JSON object properly. After you have done all the previous tasks, you have to do the following.

Note: In my case I am using a IP tracing API.

I placed a button in my XAML and now I am writing the following code in the Handler of the button:

  1. private void Json_Click(object sender, RoutedEventArgs e)  
  2. {  
  3.    WebClient webClient = new WebClient();  
  4.   
  5.    //Made Object of WebClient  
  6.    webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted   );  
  7.   
  8.   
  9.    webClient.DownloadStringAsync(new Uri("http://ip-api.com/json"));  
  10.    //Placed my API's link  
  11.   
  12. }  
  13.   
  14. private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)  
  15. {  
  16.    var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);  
  17.   
  18.    // Now you may use the Object<rootObject> according to your need.  
  19. }  
Note: To resolve the errors, add the following code:
  1. using Newtonsoft.Json;  
So that was a brief tutorial about parsing JSON in Windows Phone, I hope you enjoyed it.

Personal Blog: Blend Unleashed.

 

Next Recommended Reading How to Install Windows Phone 8 SDK