Oct 1, 2012

Parsing JSON in a Windows Phone Application


I see questions regarding JSON parsing/deserializing almost everyday in Stackoverflow. Hence decided to write a blog post to show you how to easily parse JSON strings in Windows Phone applications.

***Please read entire blog for a complete overview before implementing in your applications***

I would like to divide this post into 2 categories.
One is, where you will have to parse a similar json data in many places in your application or you will use the parsed data in many instances of your code
Other is, you just parse the data once, get your values and no need of the data else where in your project i.e one time usage.

CASE I:

Step 1: 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.

I am taking this sample json data

{"MyBookList": [{"ID":5,"TYPE":"History","TITLE":"XYZbook","PRICE":"200","IMAGE":"Ekannoborti.jpg","DOWNLOADLINK":"http://www.amazon.com/"}],"success":3}

And here are the classes generated
public class MyBookList
{
    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 string DOWNLOADLINK { get; set; }
}

public class RootObject
{
    public List<MyBookList> MyBookList { get; set; }
    public int success { get; set; }
}
Now place this classes somewhere in your project, so that they are available in all the locations you require them.

Step 2: ( Here I am assuming that you get your json from a web service)
Make a web request to get the JSON response

WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri("http://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 book in rootObject.MyBookList)
    {
         Console.WriteLine(book.TITLE);
    } }

There you go, you can play with the response classes and data bind them with the UI elements :)


CASE II:

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 this sample,

String jsonData = @"{""MyBookList"": [{""ID"":5,""TYPE"":""History"",""TITLE"":""XYZbook"",""PRICE"":""200"",""IMAGE"":""Ekannoborti.jpg"",""DOWNLOADLINK"":""http://www.amazon.com/""}],""success"":3}";

And inorder to get the title of each book here

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

NOTE : For both the cases, I have used json.net for parsing the json data. You can get it from this Nuget package. And if you dont know how to install and use a Nuget package, Check Here
Hope it helps. Please dont forget to +1 or leave a comment.
Thank you
View Kishor Chandra's profile on LinkedIn

18 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This helped more than you know. Thanks so much!

    ReplyDelete
  3. this is very much help to me.nice article

    ReplyDelete
  4. I'm having a problem installing it to a Windows Phone 8 application. It says it isn't compatible? Am I doing something wrong, or does it not work with 8?

    ReplyDelete
    Replies
    1. You mean installing the nuget package ? Tell me what you did, I will try to find out what's going wrong. (mail to nkishorchandra@gmail.com)

      Delete
  5. Perfect ... I solved my problem by this blog.Thank you for that

    ReplyDelete
  6. this shows error like Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

    ReplyDelete
    Replies
    1. There may be some problem with your JSON data. Send me a sample JSON data and I will try to help you. (nkishorchandra@gmail.com)

      Delete
  7. Thank you very much! I used the second case.

    ReplyDelete
  8. Can you provide source code? Not everyone know c#... This is confusing, where to put first code? In which file? What about xaml file? Give example step by step how to create complete project in VS.

    ReplyDelete
    Replies
    1. I have added source code at the end of the post. Please check. Thanks for the comment !!

      Delete
  9. Thank you! I need it for my project

    ReplyDelete
  10. I am using a hubtile in my application and in that i want to use two types that is name and icon from json file. can you help??

    ReplyDelete
    Replies
    1. Sure, please send me your problem in detail and I will see what I could help you with . Thanks.

      Delete
  11. Awesome tutorial dear.... very nice, very easy and very simple.
    I was fad-up to search this issue, but you make it so simple.... Thanks buddy, keep it up...

    ReplyDelete