Skip to main content

How to parse JSON data with .Net C#?

There are many occasions arise when we have to get some information form websites, websites offer information to their user in different formats and JSON is one of them.

Actually you can parse JSON data in C# itself by writing some code but JSON.Net library will help a great deal.

Example 
Let's consider an example where we have to get tweets count of a webpage from twitter. Twitter provides us with an easy way to do that by simply sending a request to one of its urls

Request Sample 
https://cdn.api.twitter.com/1/urls/count.json?url=http://download.cnet.com/Free-PDF-to-JPG-Converter/3000-2016_4-75728284.html


Request Response


string Response = {"count":10,"url":"http:\/\/download.cnet.com\/Free-PDF-to-JPG-Converter\/3000-2016_4-75728284.html\/"}



Here we go, we need to get count variable from that response.

Create a Class in C# and add this code

 public class SharesCount
 {
        private int Count_;

        public int Count
        {
            get { return Count_; }
            set { Count_= value; }
        }
 }

Here you notice that text in orange color, right?

Yeah you need to make sure that class properties match the variable (Count) that we want to get from response.

string src = Response;
SharesCount m = JsonConvert.DeserializeObject<SharesCount>(src);
int count = m.Shares;


This post answer these question

How to use Newtonsoft.Json?
How to use Json.Net?
How to get Twitter tweet count for a url?

Comments

Popular posts from this blog

Setup .PK domain with Godaddy Hosting

Setup .PK domain with Godaddy Hosting STEP-1 Open domain page from your account Add your .pk domain as offsite in godaddy don't check transfer this domain to godaddy checkbox. STEP-2 Now go to Manage Hosting/Cpanel page and select Addon Domains And fill the form and add the domain STEP-3 Now go to Domains page and click your offsite domain name and open its zone file. next next Now when Zone File tab is open, scroll-down to bottom and get your name servers STEP-4 Now take these name-servers and add them on your domain's pknic account. Thanks, if you got any questions please send me an email at m.qayyum--at--live.com

PHP Tutorials: Register & Login: User registration

Part1 Part2 Part3 Part4 Part5 Part6