Technology, Smartphones, Games


How to Convert XML and JSON to C# Classes

Earlier we have posted about How to convert JSON Text to C# Class but that was using external tools or websites. Here now we will tell you how to convert a XML or JSON to C# class with out using any external tools. Of course you will need Visual studio. And this will work if the .NET framework you are using is 4.5 or higher.

Create a blank class, copy the XML or JSON you need to convert, from the Edit menu of the Visual studio select “Paste Special” and then choose “Paste JSON as classes” or “Paste XML as classes” accordingly. That is all you need to do.

Convert Jason and XML to C

If you want to convert XML result to the class you can use the following function

protected T FromXml<T>(String xml)
         {
             T returnedXmlClass = default(T);

            try
             {
                 using (TextReader reader = new StringReader(xml))
                 {
                     try
                     {
                         returnedXmlClass =
                             (T)new XmlSerializer(typeof(T)).Deserialize(reader);
                     }
                     catch (InvalidOperationException)
                     {
                         // String passed is not XML, simply return defaultXmlClass
                     }
                 }
             }
             catch (Exception ex)
             {
             }

            return returnedXmlClass;
         }

And Call it like this

string xml = File.ReadAllText(XMLPATH);

SellResponse objSellResponse= FromXml<SellResponse>(xml);

SellResponse is the class created using the Paste special option.