JSON Handling in a Console Project


In this article, we will deal with JSON handling in a Console project. 
Later, you can use this concept in any application like Windows Phone or Silverlight application.
JSON is an acronym of JavaScript Object Notation. Basically, it is a file with specified syntax rules for storing and exchanging information. Actually, it is an alternative for XML.
The format of a JSON file looks like this:
  1. {  
  2. "employees": [  
  3. "firstName":"John" , "lastName":"Doe" },   
  4. "firstName":"Anna" , "lastName":"Smith" },   
  5. "firstName":"Peter" , "lastName":"Jones" }  
Where firstName and lastName are names and John and Doe are the value of the respective names.
And, the employee is the object. Generally, an object has a curly brace ({-}).
If an object has multiple values then it is called an array of objects. We use square brackets ([-]) to denote them.
In the example above, we used a square bracket because of the multiple values of object employees.
We will now handle this JSON file in a C# Console application.
Step 1
Before anything, arrange your reference files (Newtonsoft.Json.dll) and your JSON web service. In my demo, I will use this:
(You can download the reference file from http://json.codeplex.com/)
Note: JSON Web Services are web services that return a JSON file from a Web Request. They are similar to XML Web Services.
If you try it on your Web Browser, then you get something that looks like this.
With this, we can identify the NAME and VALUES of the object. And, they are:
Step 2
So, until now we have covered all the basics of establishing the demo. So, let's start the code.
Open a new Console Project under the C# section.
Add the following few namespaces to it:
  1. using System.Net;  
  2. using System.IO;  
  3. using Newtonsoft.Json;  
  4. using Newtonsoft.Json.Linq; 
The third one is within the Newtonsoft.Json.dll file that you have included in your project.
Since we are making a request to the server for details of the IP address in JSON format. For this, at least we need an IP address.
I'm assuming my IP address, myself and it is:
  1. //User Input  
  2.   string IPAddress = ""
Or, you may go with this:
  1. Console.WriteLine("Your IP Address  is : ");  
  2. IPAddress = Console.ReadLine(); 
Set a URI for the web request as in the following:
  1. string apiUrl = "http://freegeoip.net/json/" + IPAddress; 
We will now send a web request to apiUri as in the following:
  1. //Send webRequest  
  2.         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);  
  3.         //Get the Web Response  
  4.         HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
And parse the web response in a HttpWebResponse object, in other words, response.
  1. //Now, create the Stream  
  2. Stream responseStream = response.GetResponseStream();  
  3. //Seting Up the Stream Reader  
  4.  StreamReader readerStream = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8")); 
Now, we are establishing a stream between a web server and a web browser. After that, we have converted the response in a Human Readable language (UTF-8). Further, we can process the JSON data.
  1. //Get in a STring  
  2. string json = readerStream.ReadToEnd(); 
Store the entire JSON text (web response) in a string type.
  1. //Close the Stream  
  2. readerStream.Close(); 
Close the Stream.
It's time to extract the data from the JSON file.
For that, we must convert it into a JObject.
  1. var jo = JObject.Parse(json); 
Now, we try to get the Object Values. Since JObject treats its Name with an index name.
  1. Console.WriteLine("Country : "+(string)jo["country_name"]);  
  2. Console.WriteLine("Country Code : " + (string)jo["country_code"]);  
  3. Console.WriteLine("Region Code : " + (string)jo["region_code"]);  
  4. Console.WriteLine("City : " + (string)jo["city"]);  
  5.   Console.WriteLine("Zip Code :"+(string)jo["zipcode"]);  
  6.   Console.WriteLine("Latitude :"+(string)jo["latitude"]);  
  7.  Console.WriteLine("Longitude :" + (string)jo["longitude"]); 
That's it.
We will conclude our project.
  1. Console.ReadKey();