using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace NFine.Code
{
public static class Serialize
{
///
/// 获取对象序列化的二进制版本
///
/// 对象实体
/// 如果对象实体为Null,则返回结果为Null。
public static byte[] GetBytes(object pObj)
{
if (pObj == null) { return null; }
MemoryStream serializationStream = new MemoryStream();
new BinaryFormatter().Serialize(serializationStream, pObj);
serializationStream.Position = 0L;
byte[] buffer = new byte[serializationStream.Length];
serializationStream.Read(buffer, 0, buffer.Length);
serializationStream.Close();
return buffer;
}
///
/// 获取对象序列化的XmlDocument版本
///
/// 对象实体
/// 如果对象实体为Null,则返回结果为Null。
public static XmlDocument GetXmlDoc(object pObj)
{
if (pObj == null) { return null; }
XmlSerializer serializer = new XmlSerializer(pObj.GetType());
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
serializer.Serialize((TextWriter)writer, pObj);
XmlDocument document = new XmlDocument();
document.LoadXml(sb.ToString());
writer.Close();
return document;
}
///
/// 从已序列化数据中(byte[])获取对象实体
///
/// 要返回的数据类型
/// 二进制数据
/// 对象实体
public static T GetObject(byte[] binData)
{
if (binData == null) { return default(T); }
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream serializationStream = new MemoryStream(binData);
return (T)formatter.Deserialize(serializationStream);
}
///
/// 从已序列化数据(XmlDocument)中获取对象实体
///
/// 要返回的数据类型
/// 已序列化的文档对象
/// 对象实体
public static T GetObject(XmlDocument xmlDoc)
{
if (xmlDoc == null) { return default(T); }
XmlNodeReader xmlReader = new XmlNodeReader(xmlDoc.DocumentElement);
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(xmlReader);
}
}
}