序列化是常用的功能之一,這裡僅做一點封裝,以對大部分對象進行直接的序列化,包括:XML、BINARY、BASE64的序列化和反序列化。
一、XML序列化
注意:下面的方法並非能夠進所有的類型進行正確的序列化。
/**//// <summary>
/// 執行序列化與反序列化
/// </summary>
public class Serialize
...{
/**//// <summary>
/// 將一個對象進行XML序列化
/// </summary>
/// <param name="ObjectToSerialize">要進行序列化的對象</param>
/// <returns></returns>
public static string XMLSerialize(object ObjectToSerialize)
...{
if (ObjectToSerialize == null) return "";
StringWriter sw = new StringWriter();
XmlSerializer ser = new XMLSerializer(ObjectToSerialize.GetType());
ser.Serialize(sw, ObjectToSerialize);
string formatted = sw.ToString();
sw.Close();
return formatted;
}
/**//// <summary>
/// 將一串序列化文本反序列化為對象
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public static T XMLDeSerialize<T>(string SerializedText)
...{
StringReader sr = new StringReader(SerializedText);
XmlSerializer ser = new XMLSerializer(typeof(T));
object obj = ser.Deserialize(sr);
sr.Close();
return JCLib.Data.To<T>(obj);
}
二、二進制序列化
/**//// <summary>
/// 執行二進制序列化
/// </summary>
/// <param name="ObjectToSerialize"></param>
/// <returns></returns>
public static byte[] BinarySerialize(object ObjectToSerialize)
...{
if (ObjectToSerialize == null) return null;
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, ObjectToSerialize);
byte[] bytes = ms.ToArray();
ms.Close();
return bytes;
}
/**//// <summary>
/// 將一串序列化字節反序列化為對象
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public static T BinaryDeSerialize<T>(byte[] SerializedBytes)
...{
if (SerializedBytes == null || SerializedBytes.Length<=0) return default(T);
MemoryStream ms = new MemoryStream(SerializedBytes);
BinaryFormatter bf = new BinaryFormatter();
object obj = bf.Deserialize(ms);
ms.Close();
return JCLib.Data.To<T>(obj);
}
三、BASE64序列化
不能進行XML序列化時,使用BASE64也是不錯的選擇。下面的方法使用到[1]我的類庫:JCLib.Data類:提供數據類型轉換相關的服務中提到的Data類型的方法。
/**//// <summary>
/// 執行BASE64序列化
/// </summary>
/// <param name="ObjectToSerialize"></param>
/// <returns></returns>
public static string Base64Serialize(object ObjectToSerialize)
...{
return Data.ToBase64(BinarySerialize(ObjectToSerialize));
}
/**//// <summary>
/// 執行BASE64反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Base64SerializeedString">Base64編碼串</param>
/// <returns></returns>
public static T Base64DeSerialize<T>(string Base64SerializeedString)
...{
return BinaryDeSerialize<T>(Data.GetBytesFromBase64(Base64SerializeedString));
}