数据序列化之经验积累(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());
}
return ret;
}

public static T Deserialize<T>(string xml)
{
T ret = default(T);
if (string.IsNullOrEmpty(xml))
{
return ret;
}
using (MemoryStream stream = new MemoryStream())
{
byte[] bytes = Encoding.UTF8.GetBytes(xml);
stream.Write(bytes, 0, bytes.Length);
stream.Position = 0L;
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
using (XmlDictionaryReader binaryDictionaryReader = XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max))
{
ret = (T)serializer.ReadObject(binaryDictionaryReader);
}
}
return ret;
}
}

经过测试,本文中的序列化类,比Binary Formatter,速度要快,序列化后的结果要小,当然前提是类要用Datacontract标注,否则基本是一样的。

你可能感兴趣的:(xml)