Serialization Deserialization

on Friday, April 24, 2009

There are two kind of Serialization that you could perform on the object Xml and Binary.
Samples are below.

Suppose We have Class Animal.
[Serializable]
public class Animal
{
public Animal()

{
}
[NonSerialized]//field which doesn't required to be serialized and deserialized
public String animalName;
public String foodTypeCategory;
public Boolean isDomesticed;
}


Xml Serializer doesn't need class to be marked as Serializable while Binary Serialization does.
//Xml Serialization
class Program
{
static void Main(string[] args)
{
Animal cow = new Animal();
cow.animalName = "Cow";
cow.foodTypeCategory = "Any";

//Stream stream = File.Open("c:\\abc.xml", FileMode.Create);
MemoryStream stream = new MemoryStream();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Animal));
serializer.Serialize(stream, cow);
byte[] array = stream.GetBuffer();
stream.Close();
MemoryStream stream1 = new MemoryStream(array);

Animal obj1 = (Animal)serializer.Deserialize(stream1);
}
}

For Binary Serialization the only line which changes in the above code is XmlSerializer object creation line which will be replaced with
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new BinaryFormatter();


Also If some time you want to Control the Serialization And Deserialization of your class then you could Implement ISerializable interface and override following methods for Animal class as an example.

public Animal(SerializationInfo info, StreamingContext ctxt)
{
animalName=(String)info.GetValue("animalName",typeof(string));
foodTypeCategory = (String)info.GetValue("foodTypeCategory", typeof(string));
isDomesticed = (Boolean)info.GetValue("isDomesticed", typeof(bool));
}

public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("animalName", animalName);
info.AddValue("foodTypeCategory", foodTypeCategory);
info.AddValue("isDomesticed", isDomesticed);
}


Also If you want to convert string to byte[] and byte[] to String you could use following functions.
private String UTF8ByteArrayToString ( Byte[ ] characters )

{

UTF8Encoding encoding = new UTF8Encoding ( );

String constructedString = encoding.GetString ( characters );

return ( constructedString );

}



///



/// Converts the String to UTF8 Byte array and is used in De serialization

///


///

///

private Byte[ ] StringToUTF8ByteArray ( String pXmlString )

{

UTF8Encoding encoding = new UTF8Encoding ( );

Byte[ ] byteArray = encoding.GetBytes ( pXmlString );

return byteArray;

}

0 comments: