Serializer.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. using System;
  2. using System.Data;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Runtime.Serialization.Formatters.Binary;
  6. using System.Text;
  7. using System.Xml;
  8. using System.Xml.Serialization;
  9. using Aitex.Core.RT.Log;
  10. using Newtonsoft.Json;
  11. namespace MECF.Framework.Common.Utilities
  12. {
  13. public static class Serializer
  14. {
  15. /// <summary>Serialize the supplied object To Xml stream</summary>
  16. /// <param name="obj"></param>
  17. /// <returns></returns>
  18. public static string SerializeObjectToXmlString(object obj)
  19. {
  20. string result = "";
  21. try
  22. {
  23. XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
  24. using (StringWriter stringWriter = new StringWriter())
  25. {
  26. xmlSerializer.Serialize(stringWriter, obj);
  27. return stringWriter.ToString();
  28. }
  29. }
  30. catch (Exception ex)
  31. {
  32. LOG.Error("Failed to serialize object to XML: " + ex.StackTrace);
  33. }
  34. return result;
  35. }
  36. /// <summary>Serialize object to xml dom</summary>
  37. /// <param name="obj"></param>
  38. /// <returns></returns>
  39. public static XmlDocument SerializeObjectToXmlDom(object obj)
  40. {
  41. XmlDocument xmlDoc = new XmlDocument();
  42. try
  43. {
  44. // 创建 XmlSerializer 用于序列化对象
  45. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  46. // 使用 StringWriter 将序列化后的对象写入 XmlWriter
  47. using (StringWriter stringWriter = new StringWriter())
  48. {
  49. using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
  50. {
  51. serializer.Serialize(xmlWriter, obj);
  52. xmlDoc.LoadXml(stringWriter.ToString());
  53. }
  54. }
  55. }
  56. catch (Exception ex)
  57. {
  58. LOG.Error("Failed to serialize object to XML: " + ex.StackTrace);
  59. }
  60. return xmlDoc;
  61. }
  62. /// <summary>Serialize object to json string</summary>
  63. /// <returns></returns>
  64. public static string SerializeObjectToJsonString(object obj)
  65. {
  66. string jsonString = "";
  67. try
  68. {
  69. // Serialize the object to a JSON string
  70. jsonString = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
  71. return jsonString;
  72. }
  73. catch (Exception ex)
  74. {
  75. LOG.Error("Failed to serialize object to JSON string. " + ex.StackTrace);
  76. }
  77. return jsonString;
  78. }
  79. public static string SerializeDataTableToGZipString(DataTable dataTable)
  80. {
  81. string result = "";
  82. try
  83. {
  84. // 将 DataTable 序列化为 XML 字符串
  85. StringWriter stringWriter = new StringWriter();
  86. dataTable.WriteXml(stringWriter);
  87. string xmlString = stringWriter.ToString();
  88. // 将 XML 字符串压缩为 Gzip 格式
  89. byte[] xmlBytes = Encoding.UTF8.GetBytes(xmlString);
  90. using (MemoryStream memoryStream = new MemoryStream())
  91. {
  92. using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress))
  93. {
  94. gzipStream.Write(xmlBytes, 0, xmlBytes.Length);
  95. }
  96. result = Convert.ToBase64String(memoryStream.ToArray());
  97. }
  98. }
  99. catch (Exception ex)
  100. {
  101. LOG.Error("Failed to serialize DataTable to GZip string: " + ex.StackTrace);
  102. }
  103. return result;
  104. }
  105. public static DataTable DeserializeDataTableFromGZipString(string gZipString)
  106. {
  107. try
  108. {
  109. byte[] compressedData = Convert.FromBase64String(gZipString);
  110. using (MemoryStream memoryStream = new MemoryStream(compressedData))
  111. {
  112. using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
  113. {
  114. using (StreamReader reader = new StreamReader(gZipStream, Encoding.UTF8))
  115. {
  116. XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataTable));
  117. return (DataTable)xmlSerializer.Deserialize(reader);
  118. }
  119. }
  120. }
  121. }
  122. catch (Exception ex)
  123. {
  124. LOG.Error("Failed to deserialize DataTable from GZip string: " + ex.StackTrace);
  125. }
  126. return null;
  127. }
  128. public static string SerializeObjectToGzipString(object obj)
  129. {
  130. try
  131. {
  132. using (MemoryStream memoryStream = new MemoryStream())
  133. {
  134. // 使用 BinaryFormatter 进行对象序列化
  135. BinaryFormatter formatter = new BinaryFormatter();
  136. formatter.Serialize(memoryStream, obj);
  137. memoryStream.Seek(0, SeekOrigin.Begin);
  138. // 使用 Gzip 进行压缩
  139. using (MemoryStream compressedStream = new MemoryStream())
  140. {
  141. using (GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Compress))
  142. {
  143. memoryStream.CopyTo(gzipStream);
  144. }
  145. // 将压缩后的数据转换为 Base64 字符串
  146. byte[] compressedBytes = compressedStream.ToArray();
  147. string compressedBase64String = Convert.ToBase64String(compressedBytes);
  148. return compressedBase64String;
  149. }
  150. }
  151. }
  152. catch (Exception ex)
  153. {
  154. LOG.Error("Failed to serialize object to GZip string: " + ex.StackTrace);
  155. }
  156. return "";
  157. }
  158. public static T DeserializeObjectFromGzipString<T>(string rawString)
  159. {
  160. try
  161. {
  162. // Convert the Base64 string back to a byte array
  163. byte[] compressedData = Convert.FromBase64String(rawString);
  164. // Decompress the byte array using GZipStream
  165. using (MemoryStream memoryStream = new MemoryStream(compressedData))
  166. using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
  167. using (StreamReader reader = new StreamReader(gZipStream, Encoding.UTF8))
  168. {
  169. // Deserialize the XML data to the specified type
  170. XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
  171. return (T)xmlSerializer.Deserialize(reader);
  172. }
  173. }
  174. catch (Exception ex)
  175. {
  176. LOG.Error("Failed to deserialize object from GZip string: " + ex.StackTrace);
  177. }
  178. return default(T);
  179. }
  180. public static T DeserializeObjectFromJsonString<T>(string jsonString)
  181. {
  182. try
  183. {
  184. T result = JsonConvert.DeserializeObject<T>(jsonString);
  185. return result;
  186. }
  187. catch (Exception ex)
  188. {
  189. LOG.Error("Failed to deserialize object from JSON string. " + ex.StackTrace);
  190. }
  191. return default(T);
  192. }
  193. /// <summary>Serialize object to a xml file</summary>
  194. /// <param name="fileFullPath"></param>
  195. /// <param name="obj"></param>
  196. /// <returns></returns>
  197. public static void SerializeObjectToXmlFile(string fileFullPath, object obj)
  198. {
  199. try
  200. {
  201. XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
  202. // Ensure the directory exists
  203. string directory = Path.GetDirectoryName(fileFullPath);
  204. if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
  205. {
  206. Directory.CreateDirectory(directory);
  207. }
  208. // Serialize the object to the specified file
  209. using (StreamWriter writer = new StreamWriter(fileFullPath))
  210. {
  211. xmlSerializer.Serialize(writer, obj);
  212. }
  213. }
  214. catch (Exception ex)
  215. {
  216. LOG.Error("Failed to serialize object to Xml File: " + ex.StackTrace);
  217. }
  218. }
  219. /// <summary>Deserialize xml stream to object</summary>
  220. /// <typeparam name="T"></typeparam>
  221. /// <param name="xmlStream"></param>
  222. /// <returns></returns>
  223. public static T DeserializeObjectFromXmlStream<T>(Stream xmlStream)
  224. {
  225. try
  226. {
  227. XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
  228. return (T)xmlSerializer.Deserialize(xmlStream);
  229. }
  230. catch (Exception ex)
  231. {
  232. LOG.Error("Failed to deserialize object fromXml stream: " + ex.StackTrace);
  233. }
  234. return default(T);
  235. }
  236. /// <summary>Deserialize json file to object</summary>
  237. /// <typeparam name="T"></typeparam>
  238. /// <param name="fileFullPath"></param>
  239. /// <returns></returns>
  240. public static void SerializeObjectToJsonFile<T>(string fileFullPath, object obj)
  241. {
  242. try
  243. {
  244. // Ensure the directory exists
  245. string directory = Path.GetDirectoryName(fileFullPath);
  246. if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
  247. {
  248. Directory.CreateDirectory(directory);
  249. }
  250. // Serialize the object to a JSON string
  251. string jsonString = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
  252. // Write the JSON string to the file
  253. File.WriteAllText(fileFullPath, jsonString);
  254. Console.WriteLine("Object has been serialized and saved to JSON file.");
  255. }
  256. catch (Exception ex)
  257. {
  258. LOG.Error("Failed to serialize object to JSON file. " + ex.StackTrace);
  259. }
  260. }
  261. /// <summary>Deserialize json file to object</summary>
  262. /// <typeparam name="T"></typeparam>
  263. /// <param name="fileFullPath"></param>
  264. /// <returns></returns>
  265. public static T DeserializeObjectFromJsonFile<T>(string fileFullPath)
  266. {
  267. if (!File.Exists(fileFullPath))
  268. {
  269. throw new FileNotFoundException("The specified file was not found.", fileFullPath);
  270. }
  271. try
  272. {
  273. string jsonContent = File.ReadAllText(fileFullPath);
  274. T obj = JsonConvert.DeserializeObject<T>(jsonContent);
  275. return obj;
  276. }
  277. catch (Exception ex)
  278. {
  279. LOG.Error("Failed to deserialize object from JSON file. " + ex.StackTrace);
  280. }
  281. return default(T);
  282. }
  283. /// <summary>Deserialize xml string to object</summary>
  284. /// <param name="xmlString"></param>
  285. /// <param name="objType"></param>
  286. /// <returns></returns>
  287. public static object DeserializeObjectFromXmlString(string xmlString, Type objType)
  288. {
  289. try
  290. {
  291. XmlSerializer serializer = new XmlSerializer(objType);
  292. using (StringReader stringReader = new StringReader(xmlString))
  293. {
  294. return serializer.Deserialize(stringReader);
  295. }
  296. }
  297. catch (Exception ex)
  298. {
  299. LOG.Error("Failed to deserialize object from xml string. " + ex.StackTrace);
  300. }
  301. return null;
  302. }
  303. public static T DeserializeObjectFromXmlString<T>(string xmlString)
  304. {
  305. try
  306. {
  307. XmlSerializer serializer = new XmlSerializer(typeof(T));
  308. using (StringReader stringReader = new StringReader(xmlString))
  309. {
  310. return (T)serializer.Deserialize(stringReader);
  311. }
  312. }
  313. catch (Exception ex)
  314. {
  315. LOG.Error("Failed to deserialize object from xml string. " + ex.StackTrace);
  316. }
  317. return default(T);
  318. }
  319. /// <summary>Deserialize xml stream to object</summary>
  320. /// <param name="xmlStream"></param>
  321. /// <param name="objType"></param>
  322. /// <returns></returns>
  323. public static object DeserializeObjectFromXmlStream(Stream xmlStream, Type objType)
  324. {
  325. try
  326. {
  327. XmlSerializer serializer = new XmlSerializer(objType);
  328. return serializer.Deserialize(xmlStream);
  329. }
  330. catch (Exception ex)
  331. {
  332. LOG.Error("Failed to deserialize object from xml stream. " + ex.StackTrace);
  333. }
  334. return null;
  335. }
  336. /// <summary>Deserialize xml file to object</summary>
  337. /// <param name="xmlFileFullPath"></param>
  338. /// <param name="objType"></param>
  339. /// <returns></returns>
  340. public static object DeserializeObjectFromXmlFile(string xmlFileFullPath, Type objType)
  341. {
  342. if (!File.Exists(xmlFileFullPath))
  343. {
  344. throw new FileNotFoundException("XML file not found.", xmlFileFullPath);
  345. }
  346. try
  347. {
  348. using (FileStream xmlStream = new FileStream(xmlFileFullPath, FileMode.Open))
  349. {
  350. XmlSerializer serializer = new XmlSerializer(objType);
  351. return serializer.Deserialize(xmlStream);
  352. }
  353. }
  354. catch (Exception ex)
  355. {
  356. LOG.Error("Failed to deserialize object from xml file. " + ex.StackTrace);
  357. }
  358. return null;
  359. }
  360. /// <summary>Deserialize xml file to object</summary>
  361. /// <typeparam name="T"></typeparam>
  362. /// <param name="xmlFileFullPath"></param>
  363. /// <returns></returns>
  364. public static T DeserializeObjectFromXmlFile<T>(string xmlFileFullPath)
  365. {
  366. if (!File.Exists(xmlFileFullPath))
  367. {
  368. throw new FileNotFoundException("XML file not found.", xmlFileFullPath);
  369. }
  370. try
  371. {
  372. using (FileStream xmlStream = new FileStream(xmlFileFullPath, FileMode.Open))
  373. {
  374. XmlSerializer serializer = new XmlSerializer(typeof(T));
  375. return (T)serializer.Deserialize(xmlStream);
  376. }
  377. }
  378. catch (Exception ex)
  379. {
  380. LOG.Error("Failed to deserialize object from xml file. " + ex.StackTrace);
  381. }
  382. return default(T);
  383. }
  384. /// <summary>Clone object in xml object</summary>
  385. /// <param name="obj"></param>
  386. /// <returns></returns>
  387. public static object CloneObjectInXml(object obj)
  388. {
  389. try
  390. {
  391. // Get the type of the object
  392. Type objType = obj.GetType();
  393. // Serialize the object to XML
  394. using (MemoryStream memoryStream = new MemoryStream())
  395. {
  396. XmlSerializer serializer = new XmlSerializer(objType);
  397. serializer.Serialize(memoryStream, obj);
  398. // Reset the memory stream position to the beginning
  399. memoryStream.Position = 0;
  400. // Deserialize the object from the XML
  401. return serializer.Deserialize(memoryStream);
  402. }
  403. }
  404. catch (Exception ex)
  405. {
  406. LOG.Error($"Failed to clone object of type {obj.GetType().Name}." + ex.StackTrace);
  407. }
  408. return null;
  409. }
  410. /// <summary>Clone object in xml object</summary>
  411. /// <param name="obj"></param>
  412. /// <returns></returns>
  413. public static T CloneObjectInXml<T>(object obj)
  414. {
  415. try
  416. {
  417. // Get the type of the object
  418. Type objType = obj.GetType();
  419. // Serialize the object to XML
  420. using (MemoryStream memoryStream = new MemoryStream())
  421. {
  422. XmlSerializer serializer = new XmlSerializer(objType);
  423. serializer.Serialize(memoryStream, obj);
  424. // Reset the memory stream position to the beginning
  425. memoryStream.Position = 0;
  426. // Deserialize the object from the XML
  427. return (T)serializer.Deserialize(memoryStream);
  428. }
  429. }
  430. catch (Exception ex)
  431. {
  432. LOG.Error($"Failed to clone object of type {obj.GetType().Name}." + ex.StackTrace);
  433. }
  434. return default(T);
  435. }
  436. /// <summary>Serialized a specified typed object into byte array</summary>
  437. /// <typeparam name="T"></typeparam>
  438. /// <param name="object1"></param>
  439. /// <returns></returns>
  440. public static byte[] SerializeValueType<T>(T object1) where T : struct
  441. {
  442. try
  443. {
  444. using (MemoryStream memoryStream = new MemoryStream())
  445. {
  446. BinaryFormatter formatter = new BinaryFormatter();
  447. formatter.Serialize(memoryStream, object1);
  448. return memoryStream.ToArray();
  449. }
  450. }
  451. catch (Exception ex)
  452. {
  453. LOG.Error($"Failed to serialize object of type {typeof(T).Name}." + ex.StackTrace);
  454. }
  455. return default(byte[]);
  456. }
  457. /// <summary>将传入字符串以GZip算法压缩后,返回Base64编码字符</summary>
  458. /// <param name="rawString">需要压缩的字符串</param>
  459. /// <returns>压缩后的Base64编码的字符串</returns>
  460. public static string GZipCompressString(string rawString)
  461. {
  462. try
  463. {
  464. byte[] rawData = Encoding.UTF8.GetBytes(rawString);
  465. using (MemoryStream compressedStream = new MemoryStream())
  466. {
  467. using (GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Compress))
  468. {
  469. gzipStream.Write(rawData, 0, rawData.Length);
  470. }
  471. // Get the compressed data from the memory stream and convert it to a base64 string
  472. return Convert.ToBase64String(compressedStream.ToArray());
  473. }
  474. }
  475. catch (Exception ex)
  476. {
  477. LOG.Error("Failed to compress string using GZip." + ex.StackTrace);
  478. }
  479. return "";
  480. }
  481. /// <summary>将传入的二进制字符串资料以GZip算法解压缩</summary>
  482. /// <param name="zippedString">经GZip压缩后的二进制字符串</param>
  483. /// <returns>原始未压缩字符串</returns>
  484. public static string GZipDecompressString(string zippedString)
  485. {
  486. try
  487. {
  488. // Decode the base64 string to get the compressed byte array
  489. byte[] compressedData = Convert.FromBase64String(zippedString);
  490. using (MemoryStream compressedStream = new MemoryStream(compressedData))
  491. {
  492. using (GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
  493. {
  494. using (StreamReader reader = new StreamReader(gzipStream, Encoding.UTF8))
  495. {
  496. // Read the decompressed string from the stream
  497. return reader.ReadToEnd();
  498. }
  499. }
  500. }
  501. }
  502. catch (Exception ex)
  503. {
  504. LOG.Error("Failed to decompress string using GZip." + ex.StackTrace);
  505. }
  506. return "";
  507. }
  508. }
  509. }