Today we are going to discuss that how can we call an API(Application Programming Interface) in windows phone of the format JSON.

JSON format is not officially supported in windows phone so we have to use a third party .dll to parse the JSON.

For this purpose we have to use NewtonSoft's .dll to deserialize the JSON Object



It can be downloaded from here,



http://json.codeplex.com/



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

To search API I would like to recommend you,



http://www.programmableweb.com/



This will help you a lot finding an API.





Quest no. 2:



After you have found an API so you need to validate that API, for that purpose you can use the following link,

http://jsonlint.com/



Quest no. 3:



For a particular type of API you need to make reference classes so you may deserialize the object casting the very class,

For this quest we have another online solution for you that generates the classes for you,



There we go,

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.



GoTo References, Add new Reference , Browse the particular .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 following code in the Handler of the button,



   private void Json_Click(object sender, RoutedEventArgs e)

        {

            WebClient webClient = new WebClient();



//Made Object of WebClient

  

         webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);





            webClient.DownloadStringAsync(new Uri("http://ip-api.com/json"));

//Placed my API's link



        }









        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

        {

            var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);

   



// Now you may use the Object<rootObject> according to your need.

   

    }





Note: To resolve the errors,

add the code ,

   

using Newtonsoft.Json;







So that was a brief tutorial about parsing JSON in windows phone, Hope you enjoyed it.

See Also

Another important place to find a huge amount of Windows Phone related articles is the TechNet Wiki itself. The best entry point is Windows Phone Resources on the TechNet Wiki.