Wednesday, January 4, 2012

C# - Serialize/Deserialize object

public static string SerObj(object rspJ)
{
string serObj = null;

MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, rspJ);
serObj = Convert.ToBase64String(ms.ToArray());

return serObj;
}

public static string SerObjXML(object rspJ, Type type)
{
string serObj = null;

MemoryStream ms = new MemoryStream();
XmlSerializer bf1 = new XmlSerializer(type);
bf1.Serialize(ms, rspJ);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
serObj = sr.ReadToEnd();

return serObj;
}

public static object DeSerObjXML(string xml, Type type)
{
XmlSerializer xs = new XmlSerializer(type);
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
return xs.Deserialize(memoryStream);
}

public static
RspTestXML DeSerObj(string stringObj)
{
RspTestXML rspTestXML = null;

byte[] theByteArray = Convert.FromBase64String(stringObj);

MemoryStream ms1 = new MemoryStream(theByteArray);
BinaryFormatter bf11 = new BinaryFormatter();
ms1.Position = 0;

rspTestXML = (
RspTestXML)bf11.Deserialize(ms1);

return rspTestXML;
}


private static Byte[] StringToUTF8ByteArray(string pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}

No comments:

Post a Comment