Useful Method To Deserialize XML Or JSON From An External API Endpoint

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()
These methods will allow you to pass an unknown type as well as the URL to API endpoint, where you are getting your data from. This makes things very straight-forward, when you want to strongly-type the data with ease.
  1. public class ApiWebRequestHelper  
  2. {  
  3.     /// <summary>  
  4.     /// Gets a request from an external JSON formatted API and returns a deserialized object of data.  
  5.     /// </summary>  
  6.     /// <typeparam name="T"></typeparam>  
  7.     /// <param name="requestUrl"></param>  
  8.     /// <returns></returns>  
  9.     public static T GetJsonRequest<T>(string requestUrl)  
  10.     {  
  11.         try  
  12.         {  
  13.             WebRequest apiRequest = WebRequest.Create(requestUrl);  
  14.             HttpWebResponse apiResponse = (HttpWebResponse)apiRequest.GetResponse();  
  15.   
  16.             if (apiResponse.StatusCode == HttpStatusCode.OK)  
  17.             {  
  18.                 string jsonOutput;  
  19.                 using (StreamReader sr = new StreamReader(apiResponse.GetResponseStream()))  
  20.                     jsonOutput = sr.ReadToEnd();  
  21.                       
  22.                 var jsResult = JsonConvert.DeserializeObject<T>(jsonOutput);  
  23.   
  24.                 if (jsResult != null)  
  25.                     return jsResult;  
  26.                 else  
  27.                     return default(T);  
  28.             }  
  29.             else  
  30.             {  
  31.                 return default(T);  
  32.             }  
  33.         }  
  34.         catch (Exception ex)  
  35.         {  
  36.             // Log error here.  
  37.   
  38.             return default(T);  
  39.         }  
  40.     }  
  41.   
  42.     /// <summary>  
  43.     /// Gets a request from an external XML formatted API and returns a deserialized object of data.  
  44.     /// </summary>  
  45.     /// <typeparam name="T"></typeparam>  
  46.     /// <param name="requestUrl"></param>  
  47.     /// <returns></returns>  
  48.     public static T GetXmlRequest<T>(string requestUrl)  
  49.     {  
  50.         try  
  51.         {  
  52.             WebRequest apiRequest = WebRequest.Create(requestUrl);  
  53.             HttpWebResponse apiResponse = (HttpWebResponse)apiRequest.GetResponse();  
  54.   
  55.             if (apiResponse.StatusCode == HttpStatusCode.OK)  
  56.             {  
  57.                 string xmlOutput;  
  58.                 using (StreamReader sr = new StreamReader(apiResponse.GetResponseStream()))  
  59.                     xmlOutput = sr.ReadToEnd();  
  60.   
  61.                 XmlSerializer xmlSerialize = new XmlSerializer(typeof(T));  
  62.   
  63.                 var xmlResult = (T)xmlSerialize.Deserialize(new StringReader(xmlOutput));  
  64.   
  65.                 if (xmlResult != null)  
  66.                     return xmlResult;  
  67.                 else  
  68.                     return default(T);  
  69.             }  
  70.             else  
  71.             {  
  72.                 return default(T);  
  73.             }  
  74.         }  
  75.         catch (Exception ex)  
  76.         {  
  77.             // Log error here.
  78.             return default(T);  
  79.         }  
  80.     }  
  81. }  
ApiWebRequestHelper class relies on the following namespaces:
  • Newtonsoft Json
  • System.Xml.Serialization
  • ​​System.IO
ApiWebRequestHelper can be used in the following way:
  1. // Get Json Request  
  2. ApiWebRequestHelper.GetJsonRequest<MyJsonClassObject>("http://www.c-sharpcorner.com/api/result.json");  
  3.   
  4. // Get XML Request  
  5. ApiWebRequestHelper.GetXmlRequest<MyXMLClassObject>("http://www.c-sharpcorner.com/api/result.xml");
Ebook Download
View all
Learn
View all