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.
- public class ApiWebRequestHelper
- {
-
-
-
-
-
-
- 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)
- {
-
-
- return default(T);
- }
- }
-
-
-
-
-
-
-
- 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)
- {
-
- 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:
-
- ApiWebRequestHelper.GetJsonRequest<MyJsonClassObject>("http://www.c-sharpcorner.com/api/result.json");
-
-
- ApiWebRequestHelper.GetXmlRequest<MyXMLClassObject>("http://www.c-sharpcorner.com/api/result.xml");