JSON Handling in a Console Project

In this article we will deal with JSON handling in a Console project.

Introduction

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.



Background

JSON is an acronym of JavaScript Object Notation. Basically, it is a file with a specified syntax rules for storing and exchanging information. Actually, it is an alternative for XML.

The format of a JSON file look like this:

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" }, 
{ "firstName":"Anna" , "lastName":"Smith" }, 
{ "firstName":"Peter" , "lastName":"Jones" }
]


Where, firstName and lastName are names and John and Doe are the value of the respective names.

And, employee is the object. Generally, an object has 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.
 
Procedures

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/)
 
http://freegeoip.net/json/<ip-address>

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:
 

 

Name

Values

ip

117.214.61.178

country_code

IN

country_name

India

region_code

 

City

 

zipcode

 

latitude

20

longitude

77

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 C# section.

Add the following few namespaces to it:

using System.Net;

using System.IO;

using Newtonsoft.Json;

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:

//User Input

  string IPAddress = "117.201.110.42";

 

Or, you may go with this:

 

Console.WriteLine("Your IP Address  is : ");

IPAddress = Console.ReadLine();

 

Set a URI for the web request as in the following:

string apiUrl = "http://freegeoip.net/json/" + IPAddress;

 

We will now send a web request to apiUri as in the following:

    //Send webRequest

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);

            //Get the Web Response

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();


And parse the web response in a HttpWebResponse object, in other words response.

 //Now, create the Stream

 Stream responseStream = response.GetResponseStream();

 //Seting Up the Stream Reader

  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.

Then,

//Get in a STring

string json = readerStream.ReadToEnd();

 

Store the entire JSON text (web response) in a string type.

 

    //Close the Stream

    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.

 

   var jo = JObject.Parse(json);


Now, we try to get the Object Values. Since JObject treats its Name with an index name.

Console.WriteLine("Country : "+(string)jo["country_name"]);

Console.WriteLine("Country Code : " + (string)jo["country_code"]);

Console.WriteLine("Region Code : " + (string)jo["region_code"]);

Console.WriteLine("City : " + (string)jo["city"]);

  Console.WriteLine("Zip Code :"+(string)jo["zipcode"]);

  Console.WriteLine("Latitude :"+(string)jo["latitude"]);

 Console.WriteLine("Longitude :" + (string)jo["longitude"]);


That's it.

We will conclude our project.

Console.ReadKey();


Output



More JSON API:

http://pincodr.abhinav.co/pin/<PIN-Number>

https://www.mashape.com/