Tuesday 22 May 2012

Object to XML Conversion in C#


Sample XML is given below
<?xml version="1.0"?>
<note>
    <to>Sumesh</to>
    <from>Ramesh</from>
    <heading>greetings</heading>
    <body>How are you doing</body>
</note>

XML is widely using in data exchange , here is code for generic function for converting object to xml


       public static string ToXML(this object o, Type t)
        {
            string XmlizedString = null;
            MemoryStream memoryStream = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(t);
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);          
            xs.Serialize(xmlTextWriter, o);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
            return XmlizedString;


        }

 private static String UTF8ByteArrayToString(Byte[] characters)
        {


            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }






JSON Conversion

Conversion of JSON string to object using generic function in  c# 

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is using widely in data exchange 

Generic functions 

Generic methods have type parameters. They provide a way to parameterize the types used in a method. This means you can provide only one implementation and call it with different types. Generic methods require an unusual syntax form for more information on generic methods Click here

using System.Runtime.Serialization.Json;

public static  class Utilities
{
  public static T Deserialize<T>(string jsonString)
         {
             
                 using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
                 {
                     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                     return (T)serializer.ReadObject(ms);
                 }
            
         }
}
Above function accept string and return type and convert it to object as specified in return type.

Calling generic  function 

List<.RequestsType>objLstResponse=new List<.RequestsType>();

objLstResponse=Utilities.Deserialise<List<.RequestsType>>(response);