数据序列化之经验积累(2) -- Datacontract formatter
此文中的序列化类,主要是利用DataContractSerializer 来实现,对于标注了Datacontract的类特别有用。
二进制序列化:
public static class DataContractFormatSerializer
{
public static string SerializeToBase64String<T>(T obj, bool compress)
{
byte[] ret = Serialize<T>(obj, compress);
return Convert.ToBase64String(ret);
}public static byte[] Serialize<T>(T obj, bool compress)
{
if (obj == null)
{
return null;
}
byte[] info;
using (MemoryStream stream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
using (XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream))
{
serializer.WriteObject(binaryDictionaryWriter, obj);
binaryDictionaryWriter.Flush();
}
info = stream.ToArray();
if (compress)
{
info = CompressHelper.CompressBytes(info);
}
}
return info;
}public static T DeserializeFromBase64String<T>(string baseString, bool decompress)
{
if (String.IsNullOrEmpty(baseString))
return default(T);byte[] buffer = Convert.FromBase64String(baseString);
return Deserialize<T>(buffer, decompress);
}public static T Deserialize<T>(byte[] info, bool decompress)
{
T ret = default(T);
if (info == null || info.Length <= 0)
{
return ret;
}
if (decompress)
{
info = CompressHelper.DeCompressBytes(info);
}
using (MemoryStream stream = new MemoryStream(info))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
using (XmlDictionaryReader binaryDictionaryReader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))
{
ret = (T)serializer.ReadObject(binaryDictionaryReader);
}
}
return ret;
}
}xml:
public static class DataContractXmlSerializer
{
public static string Serialize<T>(T obj)
{
if (obj == null)
{
return null;
}
string ret = "";
using (MemoryStream stream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
using (XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
{
serializer.WriteObject(binaryDictionaryWriter, obj);
binaryDictionaryWriter.Flush();
}
ret = Encoding.UTF8.GetString(stream.ToArray());
}
&n
补充:综合编程 , 其他综合 ,