Introduction
With the ever increasing number of API interfaces becoming available to allow us to utilize data from the external platforms into our Web or software Applications, I decided to create a simple but very useful helper class that will allow for the consumption of any XML or JSON request for deserialization into a class object of your choosing.
ApiWebRequestHelper Methods
As you can see from the code, given below, ApiRequestHelper class contains two methods:
- GetJsonRequest()
- GetXmlRequest()
- public class ApiWebRequestHelper
- {
- /// <summary>
- /// Gets a request from an external JSON formatted API and returns a deserialized object of data.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="requestUrl"></param>
- /// <returns></returns>
- public static T GetJsonRequest<T>(string requestUrl)
- {
- try
- {
- WebRequest apiRequest = WebRequest.Create(requestUrl);
- HttpWebResponse apiResponse = (HttpWebResponse)apiRequest.GetResponse();
- if (apiResponse.StatusCode == HttpStatusCode.OK)
- {
- string jsonOutput;
- using (StreamReader sr = new StreamReader(apiResponse.GetResponseStream()))
- jsonOutput = sr.ReadToEnd();
- var jsResult = JsonConvert.DeserializeObject<T>(jsonOutput);
- if (jsResult != null)
- return jsResult;
- else
- return default(T);
- }
- else
- {
- return default(T);
- }
- }
- catch (Exception ex)
- {
- // Log error here.
- return default(T);
- }
- }
- /// <summary>
- /// Gets a request from an external XML formatted API and returns a deserialized object of data.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="requestUrl"></param>
- /// <returns></returns>
- public static T GetXmlRequest<T>(string requestUrl)
- {
- try
- {
- WebRequest apiRequest = WebRequest.Create(requestUrl);
- HttpWebResponse apiResponse = (HttpWebResponse)apiRequest.GetResponse();
- if (apiResponse.StatusCode == HttpStatusCode.OK)
- {
- string xmlOutput;
- using (StreamReader sr = new StreamReader(apiResponse.GetResponseStream()))
- xmlOutput = sr.ReadToEnd();
- XmlSerializer xmlSerialize = new XmlSerializer(typeof(T));
- var xmlResult = (T)xmlSerialize.Deserialize(new StringReader(xmlOutput));
- if (xmlResult != null)
- return xmlResult;
- else
- return default(T);
- }
- else
- {
- return default(T);
- }
- }
- catch (Exception ex)
- {
- // Log error here.
- return default(T);
- }
- }
- }
ApiWebRequestHelper class relies on the following namespaces:
- Newtonsoft Json
- System.Xml.Serialization
- System.IO
ApiWebRequestHelper can be used in the following way:
- // Get Json Request
- ApiWebRequestHelper.GetJsonRequest<MyJsonClassObject>("http://www.c-sharpcorner.com/api/result.json");
- // Get XML Request
- ApiWebRequestHelper.GetXmlRequest<MyXMLClassObject>("http://www.c-sharpcorner.com/api/result.xml");

kalu singh raoPosted Jul 18, 2016, 2:04 AM
Nice...