码迷,mamicode.com
首页 > 其他好文 > 详细

序列化与反序列化

时间:2019-09-23 22:47:47      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:col   mes   ati   buffer   uil   去除   序列   nbsp   factory   

 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

 

序列化与反序列化

标签:col   mes   ati   buffer   uil   去除   序列   nbsp   factory   

原文地址:https://www.cnblogs.com/hugeboke/p/11575208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!