Communicate with Web Service Using WebClient

  There was a requirement in one of our project, to  deserialize the response from a web service to a .Net object using c#. To address this requirement we have used WebClient object.WebClient is a powerful class provided by .Net. This class is found in the System.Net namespace. There are many uses of the class. Generally it is used to interact with a web URL and handle the response from the URL. Here I am explaining how to use it’s one of the most important method “.DownloadString(ServiceUrl)” . 

Here the ServiceUrl is the url to the web service. This method download the response contents as string/json format.Here in the following example, I am getting the response as string /JSON format and I am deserializing  the response to a .Net object.

ServiceUrl = “http://knowledge-junction.com/api/status?site=example.com”;

WebClient _WebClient = new WebClient();

_WebClient.UseDefaultCredentials = true;

_myWebClient.Proxy.Credentials = CredentialCache.DefaultCredentials;

string serviceResponse = _WebClient.DownloadString(ServiceUrl);

 

After getting the response from service, my response was look like following string.

{“Site url” : “example.com “,”Required Url”: null ,”city”:”Pune”,”Users”:[ {“Name” :”Manas”,”Age”,”38″},{“Name”,”A.Rasmi”,”Age”,”50″ }]}

I have my .Net object ready with all required properties as with following class structure.

public class UserServiceResponse {

public string Url { get; set; }

public object RequiredUrl { get; set; }

public string City { get; set; }

public List<User> Users { get; set; }

}

public class User  {

public string Name { get; set; }

public string Age { get; set; }

}

Now I want to deserialize the response to .Net object. In this example, I have used NewTonSoft to serialized and deserialized JSON and used NuGet to install NewTonSoft to my solution.Find the following code snippet to deserialize the json response to my .net object.

UserServiceResponse userSvcResponse = new UserServiceResponse ();

if (!string.IsNullOrEmpty(serviceResponse))  {

userSvcResponse = JsonConvert.DeserializeObject<UserServiceResponse> (serviceResponse );

}

Once our deserialization done, we can use our UserServiceResponse object as per our requirement. I hope this helps you.

Thanks for reading this blog 🙂

Feel free to get in touch for any feedback / issue / comments / doubts

 

Advertisements

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.