序列化与反序列化
Posted hugeboke
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了序列化与反序列化相关的知识,希望对你有一定的参考价值。
1 #region 序列化 2 public static string Serializer<T>(T t) 3 { 4 //StringBuilder sb = new StringBuilder(); 5 using (MemoryStream ms = new MemoryStream()) 6 { 7 using (System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8)) 8 { 9 XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory(); 10 string name = t.GetType().Name; 11 12 XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); 13 //Add an empty namespace and empty value 14 ns.Add("", ""); 15 16 XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(typeof(T)); 17 18 xmlSerializer.Serialize(xw, t); 19 20 // 去除BOM 21 byte[] buffer = ms.ToArray(); 22 23 if (buffer.Length <= 3) 24 { 25 return Encoding.UTF8.GetString(buffer); 26 } 27 byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf }; 28 if (buffer[0] == bomBuffer[0] && buffer[1] == bomBuffer[1] && buffer[2] == bomBuffer[2]) 29 { 30 return Encoding.UTF8.GetString(buffer, 3, buffer.Length - 3); 31 } 32 return Encoding.UTF8.GetString(buffer); 33 } 34 } 35 } 36 #endregion 37 38 #region 反序列化 39 public static T Deserialize<T>(string xml) 40 { 41 using (StringReader reader = new StringReader(xml)) 42 { 43 XmlSerializer xs = new XmlSerializer(typeof(T)); 44 T obj = (T)xs.Deserialize(reader); 45 return obj; 46 } 47 } 48 #endregion
以上是关于序列化与反序列化的主要内容,如果未能解决你的问题,请参考以下文章