序列化和反序列化

前端之家收集整理的这篇文章主要介绍了序列化和反序列化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

序列化:将实体对象序列化为指定格式,如序列化为XML文件又或者是序列化为JSON字符串等。
反序列化:将XML文件或者JSON字符串等转换为实体对象。

准备实体数据

1.首先新建一个控制台工程,建立实体Company(公司类)、Employee(员工类)、ESex(性别枚举)

  1. public class Company
  2. {
  3. /// <summary>
  4. /// 公司名称
  5. /// </summary>
  6. public string Name { get; set; }
  7. /// <summary>
  8. /// 注册时间
  9. /// </summary>
  10. public DateTime RegistrationTime { get; set; }
  11. /// <summary>
  12. /// 注册资金
  13. /// </summary>
  14. public int RegistrationCapital { get; set; }
  15. /// <summary>
  16. /// 公司员工
  17. /// </summary>
  18. public List<Employee> employees { get; set; }
  19.  
  20. public override string ToString()
  21. {
  22. return string.Format("Name:{0}\nRegistrationTime:{1}\nRegistrationCapital:{2}\nemployeesNumber:{3}",Name,RegistrationTime.ToString("yyyy-MM-dd HH:mm:ss"),RegistrationCapital,employees.Count());
  23. }
  24. }
  25. public class Employee
  26. {
  27. /// <summary>
  28. ///员工名称
  29. /// </summary>
  30. public string Name { get; set; }
  31. /// <summary>
  32. /// 入职时间
  33. /// </summary>
  34. public DateTime InductionTime { get; set; }
  35. /// <summary>
  36. /// 年龄
  37. /// </summary>
  38. public int Age { get; set; }
  39. /// <summary>
  40. /// 性别
  41. /// </summary>
  42. public ESex Sex { get; set; }
  43. public override string ToString()
  44. {
  45. return string.Format("Name:{0}\nInductionTime:{1}\nAge:{2}\nSex:{3}",InductionTime.ToString("yyyy-MM-dd HH:mm:ss"),Age,Sex);
  46. }
  47. }
  48. public enum ESex
  49. {
  50. man,woman
  51. }

2.准备测试数据

  1. #region 准备测试数据
  2. List<Employee> ems = new List<Employee>() {
  3. new Employee(){ Age=22,InductionTime=new DateTime(2012,2,1),Name="张三",Sex=ESex.man},new Employee(){ Age=32,5,Name="李四",new Employee(){ Age=18,InductionTime=new DateTime(2014,7,5),Name="赵婷",Sex=ESex.woman}
  4. };
  5. Company company = new Company()
  6. {
  7. Name = "上海点点乐信息科技有限公司",RegistrationCapital = 5000000,RegistrationTime = new DateTime(2012,1,employees = ems
  8.  
  9. };
  10. #endregion

序列化XML

对于XML的序列化和反序列化我们需要用到System.Xml.Serialization.XmlSerializer 类

分析需求得出,需要将什么类型的对象序列化为XML,XML文件的保存路径是什么,如果当前路径目录不存在,还需要先创建目录。

  1. /// <summary>
  2. /// 创建目录和文件
  3. /// </summary>
  4. /// <param name="path">路径</param>
  5. /// <param name="isfile">路径是否是文件(默认是)</param>
  6. /// <returns></returns>
  7. public static bool CreateFileToDirectory(string path,bool isfile = true)
  8. {
  9. FileStream fs = null;
  10. try
  11. {
  12. if (!isfile)
  13. {
  14. if (!System.IO.Directory.Exists(path))
  15. Directory.CreateDirectory(path);
  16. }
  17. else
  18. {
  19. string directorypath = path.Substring(0,path.LastIndexOf("/"));//截取目录
  20. if (!System.IO.Directory.Exists(directorypath))
  21. Directory.CreateDirectory(directorypath);
  22.  
  23. if (!System.IO.File.Exists(path))
  24. fs = File.Create(path);
  25. }
  26. }
  27. catch (Exception ex)
  28. {
  29. throw ex;
  30. }
  31. finally
  32. {
  33. if (fs != null)
  34. fs.Close();
  35. }
  36. return true;
  37. }
  1. /// <summary>
  2. /// 序列化为XML
  3. /// </summary>
  4. /// <param name="obj">序列化对象</param>
  5. /// <param name="filepath">XML保存路径</param>
  6. /// <returns>返回true序列化成功,否则失败</returns>
  7. public static bool SerializeXml(Object obj,string filepath)
  8. {
  9. bool result = false;
  10. FileStream fs = null;
  11. try
  12. {
  13. CreateFileToDirectory(filepath);
  14. fs = new FileStream(filepath,FileMode.Create,FileAccess.Write,FileShare.ReadWrite);
  15. System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
  16. serializer.Serialize(fs,obj);
  17. result = true;
  18. }
  19. catch (Exception ex)
  20. {
  21. throw ex;
  22. }
  23. finally
  24. {
  25. if (fs != null)
  26. fs.Close();
  27. }
  28. return result;
  29. }

反序列化XML

需要将那个路径的XML文件反序列化为什么类型的实体对象?

  1. /// <summary>
  2. /// 反序列化XML
  3. /// </summary>
  4. /// <param name="type">反序列化的类型</param>
  5. /// <param name="filepath">XML文件路径</param>
  6. /// <returns>返回obj对象</returns>
  7. public static object DeserializeXml(Type type,string filepath)
  8. {
  9. FileStream fs = null;
  10. try
  11. {
  12. fs = new FileStream(filepath,FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
  13. System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
  14. return serializer.Deserialize(fs);
  15. }
  16. catch (Exception ex)
  17. {
  18. throw ex;
  19. }
  20. finally
  21. {
  22. if (fs != null)
  23. fs.Close();
  24. }
  25. }
  26. /// <summary>
  27. /// 反序列化XML
  28. /// </summary>
  29. /// <typeparam name="T">类型参数</typeparam>
  30. /// <param name="type">反序列化的类型</param>
  31. /// <param name="filepath">XML文件路径</param>
  32. /// <returns>返回T类型对象</returns>
  33. public static T DeserializeXml<T>(string filepath)
  34. {
  35. FileStream fs = null;
  36. try
  37. {
  38. fs = new FileStream(filepath,FileShare.ReadWrite);
  39. System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
  40. return (T)serializer.Deserialize(fs);
  41. }
  42. catch (Exception ex)
  43. {
  44. throw ex;
  45. }
  46. finally
  47. {
  48. if (fs != null)
  49. fs.Close();
  50. }
  51. }

序列化和反序列化JSON

序列化JSON需要用到 Newtonsoft.Json.dll库,可在引用上右键管理Nuget程序搜索json.net来安装引用

  1. /// <summary>
  2. /// 序列化为JSON
  3. /// </summary>
  4. /// <param name="obj">序列化对象</param>
  5. /// <returns>返回json字符串</returns>
  6. public static string SerializeJson(Object obj)
  7. {
  8. return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  9. }
  10. /// <summary>
  11. /// 反序列化JSON
  12. /// </summary>
  13. /// <typeparam name="T">类型参数</typeparam>
  14. /// <param name="value">json字符串</param>
  15. /// <returns>返回T类型对象对象</returns>
  16. public static T DeserializeJson<T>(string value)
  17. {
  18. return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
  19. }

完整代码

IOHelper.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7.  
  8. namespace ConsoleApplication38
  9. {
  10. public sealed class IOHelper
  11. {
  12. /// <summary>
  13. /// 反序列化XML
  14. /// </summary>
  15. /// <param name="type">反序列化的类型</param>
  16. /// <param name="filepath">XML文件路径</param>
  17. /// <returns>返回obj对象</returns>
  18. public static object DeserializeXml(Type type,FileShare.ReadWrite);
  19. System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
  20. return (T)serializer.Deserialize(fs);
  21. }
  22. catch (Exception ex)
  23. {
  24. throw ex;
  25. }
  26. finally
  27. {
  28. if (fs != null)
  29. fs.Close();
  30. }
  31. }
  32. /// <summary>
  33. /// 序列化为XML
  34. /// </summary>
  35. /// <param name="obj">序列化对象</param>
  36. /// <param name="filepath">XML保存路径</param>
  37. /// <returns>返回true序列化成功,否则失败</returns>
  38. public static bool SerializeXml(Object obj,obj);
  39. result = true;
  40. }
  41. catch (Exception ex)
  42. {
  43. throw ex;
  44. }
  45. finally
  46. {
  47. if (fs != null)
  48. fs.Close();
  49. }
  50. return result;
  51. }
  52. /// <summary>
  53. /// 序列化为JSON
  54. /// </summary>
  55. /// <param name="obj">序列化对象</param>
  56. /// <returns>返回json字符串</returns>
  57. public static string SerializeJson(Object obj)
  58. {
  59. return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  60. }
  61. /// <summary>
  62. /// 反序列化JSON
  63. /// </summary>
  64. /// <typeparam name="T">类型参数</typeparam>
  65. /// <param name="value">json字符串</param>
  66. /// <returns>返回T类型对象对象</returns>
  67. public static T DeserializeJson<T>(string value)
  68. {
  69. return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
  70. }
  71. /// <summary>
  72. /// 创建目录和文件
  73. /// </summary>
  74. /// <param name="path">路径</param>
  75. /// <param name="isfile">路径是否是文件(默认是)</param>
  76. /// <returns></returns>
  77. public static bool CreateFileToDirectory(string path,path.LastIndexOf("/"));//截取目录
  78. if (!System.IO.Directory.Exists(directorypath))
  79. Directory.CreateDirectory(directorypath);
  80.  
  81. if (!System.IO.File.Exists(path))
  82. fs = File.Create(path);
  83. }
  84. }
  85. catch (Exception ex)
  86. {
  87. throw ex;
  88. }
  89. finally
  90. {
  91. if (fs != null)
  92. fs.Close();
  93. }
  94. return true;
  95. }
  96. }
  97. }

Program.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace ConsoleApplication38
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. #region 准备测试数据
  15. List<Employee> ems = new List<Employee>() {
  16. new Employee(){ Age=22,employees = ems
  17.  
  18. };
  19. #endregion
  20.  
  21. #region 序列化XML
  22. if (IOHelper.SerializeXml(company,"../Config/CompanyConfig.config"))
  23. Console.WriteLine("序列化成功");
  24. else
  25. Console.WriteLine("序列化失败");
  26. Console.WriteLine("===============================华丽的分割线===============================");
  27. if (IOHelper.SerializeXml(ems,"../Config/EmployeeConfig.config"))
  28. Console.WriteLine("序列化成功");
  29. else
  30. Console.WriteLine("序列化失败");
  31. #endregion
  32.  
  33. Console.WriteLine("===============================华丽的分割线===============================");
  34.  
  35. #region 反序列化XML
  36. Company x_company = (Company)IOHelper.DeserializeXml(typeof(Company),"../Config/CompanyConfig.config");
  37. Console.WriteLine(x_company.ToString());
  38. foreach (var item in x_company.employees)
  39. {
  40. Console.WriteLine(item.ToString());
  41. }
  42.  
  43. Console.WriteLine("===============================华丽的分割线===============================");
  44.  
  45. List<Employee> x_employees = IOHelper.DeserializeXml<List<Employee>>("../Config/EmployeeConfig.config");
  46. foreach (var item in x_employees)
  47. {
  48. Console.WriteLine(item.ToString());
  49. }
  50. #endregion
  51.  
  52. Console.WriteLine("===============================华丽的分割线===============================");
  53.  
  54. #region 序列化JSON
  55. string json_company = IOHelper.SerializeJson(company);
  56. Console.WriteLine(IOHelper.SerializeJson(json_company));
  57.  
  58. Console.WriteLine("===============================华丽的分割线===============================");
  59.  
  60. string json_ems = IOHelper.SerializeJson(ems);
  61. Console.WriteLine(json_ems);
  62. #endregion
  63.  
  64. Console.WriteLine("===============================华丽的分割线===============================");
  65.  
  66. #region 反序列化JSON
  67. Company j_company = IOHelper.DeserializeJson<Company>(json_company);
  68. Console.WriteLine(j_company.ToString());
  69. foreach (var item in j_company.employees)
  70. {
  71. Console.WriteLine(item.ToString());
  72. }
  73.  
  74. Console.WriteLine("===============================华丽的分割线===============================");
  75.  
  76. List<Employee> j_employees = IOHelper.DeserializeJson<List<Employee>>(json_ems);
  77. foreach (var item in j_employees)
  78. {
  79. Console.WriteLine(item.ToString());
  80. }
  81. #endregion
  82. }
  83.  
  84. }
  85. public class Company
  86. {
  87. /// <summary>
  88. /// 公司名称
  89. /// </summary>
  90. public string Name { get; set; }
  91. /// <summary>
  92. /// 注册时间
  93. /// </summary>
  94. public DateTime RegistrationTime { get; set; }
  95. /// <summary>
  96. /// 注册资金
  97. /// </summary>
  98. public int RegistrationCapital { get; set; }
  99. /// <summary>
  100. /// 公司员工
  101. /// </summary>
  102. public List<Employee> employees { get; set; }
  103.  
  104. public override string ToString()
  105. {
  106. return string.Format("Name:{0}\nRegistrationTime:{1}\nRegistrationCapital:{2}\nemployeesNumber:{3}",woman
  107. }
  108. }

猜你在找的XML相关文章