整理一下.net的三种主流序列话方式,方便ctrl+c,v 。还少Json.net的序列化方式,因为最近用那个发现点问题,正在研究他的源代码,有了结论再发。还有自定义流协议(方便跨平台),有个代码生成器,有时间整理一下单独发出来。
一、流方式:
//序列化
MemoryStream memStream = new MemoryStream();
new BinaryFormatter().Serialize(memStream, obj);
var buf= memStream.GetBuffer();
//反序列化
MemoryStream memStream = new MemoryStream(buf);
object obj = new BinaryFormatter().Deserialize(memStream);
MemoryStream memStream = new MemoryStream();
new BinaryFormatter().Serialize(memStream, obj);
var buf= memStream.GetBuffer();
//反序列化
MemoryStream memStream = new MemoryStream(buf);
object obj = new BinaryFormatter().Deserialize(memStream);
二、xml方式:
//序列化:
XmlSerializer xs = new XmlSerializer(typeof(obj));
MemoryStream memStream = new MemoryStream ();
xs.Serialize(memStream , obj);
//反序列化:
XmlSerializer xs = new XmlSerializer(typeof(obj));
MemoryStream memStream = new MemoryStream ();
XmlSerializer xs = new XmlSerializer(typeof(obj));
MemoryStream memStream = new MemoryStream ();
xs.Serialize(memStream , obj);
//反序列化:
XmlSerializer xs = new XmlSerializer(typeof(obj));
MemoryStream memStream = new MemoryStream ();
boject obj = xs.Deserialize(memStream);
三、Json方式:
//序列化:
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
MemoryStream memStream = new MemoryStream();
js.WriteObject(memStream, obj);
string jStr = Encoding.UTF8.GetString(ms.ToArray());
//反序列化:
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(jStr));
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
MemoryStream memStream = new MemoryStream();
js.WriteObject(memStream, obj);
string jStr = Encoding.UTF8.GetString(ms.ToArray());
//反序列化:
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(jStr));
object obj = js.ReadObject(memStream);
四、自定义
一般是自定义的流协议,配合代码生成器,可以实现各种设备间无障碍通讯(本人在无线开发、网游开发中常用此方法),可以考虑把代码生成器整理一下公布出来,现在看还比较烂;)