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
Comments
- Anonymous
February 25, 2013
This is very useful blog, I need it for my coming project. thanks - Anonymous
June 21, 2013
thanks for using my blog post :)nkishorchandra.blogspot.in/.../parsing-json-in-windows-phone.html - Anonymous
July 08, 2013
Where did you get this from "JsonConvert" - Anonymous
November 18, 2013
For anyone else having issues with "The name 'JsonConvert' does not exist in the current context", make sure you install the required NuGet package (http://json.codeplex.com/) via the Package Manager, and then add to your .cs file 'using Newtonsoft.Json;'. - Anonymous
November 27, 2013
if ((position.X > 196 && position.X < 290) && (position.Y > 28 && position.Y < 126)) { } - Anonymous
January 01, 2014
Thank you a lot Jamie Hoyle, saved me hours of search. - Anonymous
May 07, 2014
very useful. rameshkumarp.weebly.com - Anonymous
May 08, 2014
The comment has been removed - Anonymous
May 19, 2014
Very Use full - Anonymous
August 11, 2014
Is this solution effective for windows phone 7.1? - Anonymous
September 02, 2014
Hi,I got stuck at step 2 . I have followed the procedure mentioned in step 1.Please be brief with a exampleIam getting the error :object does not definition for "Data" and no extension method "Data" accepting a first argument of type 'object could be found" Are you missing directive or an assembly reference.at void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e){var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);foreach (var blog in rootObject.Data){Console.WriteLine(blog.title);}}As my generated clases are:public class Data{ public List<string> cat { get; set; } public List<string> churl { get; set; } public List<string> disc { get; set; } public List<string> id { get; set; } public List<string> imgpath { get; set; } public List<string> title { get; set; } public List<string> udate { get; set; } public List<string> vodid { get; set; } public List<string> vtype { get; set; }}public class Hit{ public string id { get; set; } public Data data { get; set; }}public class Hits{ public int found { get; set; } public int start { get; set; } public List<Hit> hit { get; set; }}public class Info{ public string rid { get; set; } public int __invalid_name__time-ms { get; set; } public int __invalid_name__cpu-time-ms { get; set; }}public class RootObject{ public string rank { get; set; } public string __invalid_name__match-expr { get; set; } public Hits hits { get; set; } public Info info { get; set; }}my xaml.cs file looks asWebClient webClient = new WebClient();webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);webClient.DownloadStringAsync(new Uri(my json url));void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e){var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);foreach (var blog in rootObject.Datat){Console.WriteLine(blog.title);}} - Anonymous
September 02, 2014
correction : foreach (var blog in rootObject.Data)