Parsing JSON in Windows Phone Apps

This blog is intended to show you how you can easily parse JSON strings in Windows Phone applications. If you are intending to reuse your parsed JSON across the project then go for the 1st Method, Otherwise if it is a one time usage, you can parse the data and that's it then go for the 2nd Method.

1st Method: Parsing and Reusing JSON Objects

  • Step1: Go to Json2Csharp site and paste either your entire JSON string or URL to the JSON and click on Generate button. This creates all the required classes for your JSON response.

For example, this JSON dataset:

 {"MyBlogList":[{"ID":9,"TYPE":"WindowsPhone","TITLE":"XYZ","PRICE":"0","IMAGE":"Post1.jpg"}],"success":3}

The generated class object is:

  public class MyBlogList
 {
 public int ID { get; set; }
 public string TYPE { get; set; }
 public string TITLE { get; set; }
 public string PRICE { get; set; }
 public string IMAGE { get; set; }
 }
 public class RootObject
 {
 public List<MyBlogList> MyBlogList { get; set; }
 public int success { get; set; }
 }

Now place this class somewhere in your project, so that it will be available in the required locations.

  • Step 2: (i.e. assuming that you get your JSON from a web service), Make a web request to get the JSON response

You will have to use the WebClient class as well as enabling the DownloadStringCompleted Event handler which returns the response to be manipulated.

 WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(https://somedomain.com/xyz/myjson.aspx)); 

And then in the response handler, use the following code to parse the data and convert into classes:

 void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 {
 var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result); 
 foreach (var blog in rootObject.MyBlogList) 
 { 
 Console.WriteLine(blog.TITLE);
 } 
 }

2nd Method: One Time JSON Parse

Here as your requirement is one time parsing and one time usage, instead of storing them in unnecessary classes, we just wisely parse the data and get the task done.

Consider the exact same sample JSON dataset provided above, and we want to get the blog title so here is the code snippet for that:

 JObject obj = JObject.Parse(jsonData);
JArray jarr = (JArray)obj["MyBlogList"];
string blogTitle = (string)jarr[0]["TITLE"]; //To get the title of the blog 
 or
foreach(var item in jarr) 
 Console.WriteLine(item["TITLE"]); //Gets the title of each book in the list

There you go, you can play with the response and bind the data with the UI elements.

NOTE : For both the methods, I have used JSON.NET for parsing the JSON data. You can get it from this Nuget package, And if you don't know how to install and use a Nuget package, Check Here