Thursday 25 September 2014

Consuming a JSON service with C#



If you like to consume a JSON web service in C# this example might be handy.

You need to know the url (web address) of the web service

You need to understand what the web service will return


You need to know what kind of security the web service accepts (My example uses Basic Authentication)


You need to understand under which context you are consuming the service (My example uses a Proxy server to communicate)


I found a site that automatically generates a class based on the result of the JSON web service at http://json2csharp.com/. This site can generate an class either by you specifying the url to the web service or providing the JSON result from the service you wish to consume.

Lets just assume in the example that my service will return {“variable1″:1,”variable2″:”a return string”}

By definition this means one variable with an int and one with a string.
JSON2CSHARP will return a usable class for me to use in my code;

public class RootObject
{
    public int variable1 { get; set; }
    public string variable2 { get; set; }
}


Lets go ahead and add some more code to consume this now when we have a nice helper class to contain my result.

string url = “http://yourserver/service?someparams=somevalue“;

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);

string username = “username”;


string password = “********”;


// Use the CredentialCache so we can attach the authentication to the request
CredentialCache mycache = new CredentialCache();


// We want to use Basic Authentication
mycache.Add(new Uri(url), “Basic”, new NetworkCredential(username, password));


wr.Credentials = mycache;
wr.Headers.Add(“Authorization”, “Basic ” + Convert.ToBase64String(new ASCIIEncoding().GetBytes(username + “:” + password)));


// Proxy (if you do not need it – ommit it)
wr.Proxy = new WebProxy(http://proxyserver:8080);


// Get the response from the web service
HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
Stream r_stream = response.GetResponseStream();


//convert it
StreamReader response_stream = new StreamReader(r_stream, System.Text.Encoding.GetEncoding(“utf-8″));

string jSon = response_stream.ReadToEnd();

//clean up your stream
response_stream.Close();

System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

 RootObject result = jsSerializer.Deserialize<RootObject>(jSon);

No comments:

Post a Comment

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...