Blog

Blogging on programming and life in general.

Useful Method To Deserialize XML or JSON To A Class Object

Posted in: ASP.NET, C#

I have created a helper class that will allow me to consume any XML or JSON request for deserialization into a class object. As you can see from the code below, the GetJsonRequest() and GetXmlRequest() methods allow you to pass an unknown type as well as the URL to where you are getting your request from. This makes things very straight-forward when you want to easily strongly type the data.

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);
        }
    }
}

The ApiWebRequestHelper class relies on the following namespaces:

  • Newtonsoft Json
  • System.Xml.Serialization
  • ​​System.IO;

The ApiWebRequestHelper can be used in the following way:

// Get Json Request
ApiWebRequestHelper.GetJsonRequest<MyCustomJsonClass>("http://www.surinderbhomra.com/api/result.json");

// Get XML Request
ApiWebRequestHelper.GetXmlRequest<MyCustomXMLClass>("http://www.surinderbhomra.com/api/result.xml");
blog comments powered by Disqus
;