浅谈C# 序列化与反序列化几种格式的转换

时间:2022-05-16 06:59:34

这里介绍了几种方式之间的序列化与反序列化之间的转换

首先介绍的如何序列化,将object对象序列化常见的两种方式即string和xml对象;

第一种将object转换为string对象,这种比较简单没有什么可谈的;

?
1
2
3
4
5
public string ScriptSerialize<T>(T t)
    {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      return serializer.Serialize(t);
    }

第二种将object转换为xml对象:

?
1
2
3
4
5
6
7
8
9
10
11
public string ScriptSerializeToXML<T>(T t)
    {
      XmlSerializer serializer = new XmlSerializer(typeof(T));
      MemoryStream mem = new MemoryStream();
      XmlTextWriter writer = new XmlTextWriter(mem,Encoding.UTF8);
      XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
      ns.Add("","");
      serializer.Serialize(writer,t,ns);
      writer.Close();
      return Encoding.UTF8.GetString(mem.ToArray());
    }

下面我主要讲string对象反序列化为对应的对象;

一、将string对象反序列化为object对象

?
1
2
3
4
5
public T ScriptDeserialize<T>(string strJson)
    {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      return serializer.Deserialize<T>(strJson);
    }

二、将string对象反序列化为list对象

?
1
2
3
4
5
6
public List<T> JSONStringToList<T>(string strJson)
    {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      List<T> objList = serializer.Deserialize<List<T>>(strJson);
      return objList;
    }

三、将string对象反序列化为datatable对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public DataTable JSONStringToDataTable<T>(string strJson)
    {
      DataTable dt = new DataTable();
      if (strJson.IndexOf("[") > -1)//如果大于则strJson存放了多个model对象
      {
        strJson = strJson.Remove(strJson.Length - 1, 1).Remove(0, 1).Replace("},{", "};{");
      }
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      string[] items = strJson.Split(';');
 
      foreach (PropertyInfo property in typeof(T).GetProperties())//通过反射获得T类型的所有属性
      {
        DataColumn col = new DataColumn(property.Name,property.PropertyType);
        dt.Columns.Add(col);
      }
      //循环 一个一个的反序列化
      for (int i = 0; i < items.Length; i++)
      {
        DataRow dr = dt.NewRow();
        //反序列化为一个T类型对象
        T temp = serializer.Deserialize<T>(items[i]);
        foreach (PropertyInfo property in typeof(T).GetProperties())
        {
          dr[property.Name] = property.GetValue(temp,null);
        }
        dt.Rows.Add(dr);
      }
      return dt;
    }

四、将xml对象反序列化为object对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public T JSONXMLToObject<T>(string strJson)
    {
      XmlDocument xdoc = new XmlDocument();
      try
      {
        xdoc.LoadXml(strJson);
        XmlNodeReader reader = new XmlNodeReader(xdoc.DocumentElement);
        XmlSerializer ser = new XmlSerializer(typeof(T));
        object obj = ser.Deserialize(reader);
        return (T)obj;
      }
      catch
      {
        return default(T);
      }
    }

现在用具体的实例来如何调用他们呢?特别要注意的是将xml对象反序列化objcet对象

?
1
2
3
4
5
public class LoginObject
  {
     public string Account { get; set;}
     public string Password { get; set;}
   }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
LoginObject loginObject = new LoginObject { Account = account, Password = password };
      ExTools.Manage.Class.CScriptSerialize Serialize = new Class.CScriptSerialize();
      //将object对象转换为string
       string strJson=Serialize.ScriptSerialize(loginObject);
     
      //将object对象转换为xml对象
      string strJson = Serialize.ScriptSerializeToXML(loginObject);
      
 
      //转换为list对象
       List<LoginObject> list = Serialize.JSONStringToList<LoginObject>(strJson);
      //将一个xml对象转换为object对象
      strJson = strJson.Substring(1, strJson.Length - 1);
      loginObject = Serialize.JSONXMLToObject<LoginObject>(strJson);
      //将字符串转换为dataTable
      DataTable dt = Serialize.JSONStringToDataTable<LoginObject>(strJson);
      //将字符串转换为object对象
      loginObject = Serialize.ScriptDeserialize<LoginObject>(strJson);

以上这篇浅谈C# 序列化与反序列化几种格式的转换就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。