123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583 |
- using System;
- using System.Data;
- using System.IO;
- using System.IO.Compression;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Text;
- using System.Xml;
- using System.Xml.Serialization;
- using Aitex.Core.RT.Log;
- using Newtonsoft.Json;
- namespace MECF.Framework.Common.Utilities
- {
- public static class Serializer
- {
- /// <summary>Serialize the supplied object To Xml stream</summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string SerializeObjectToXmlString(object obj)
- {
- string result = "";
- try
- {
- XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
- using (StringWriter stringWriter = new StringWriter())
- {
- xmlSerializer.Serialize(stringWriter, obj);
- return stringWriter.ToString();
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to serialize object to XML: " + ex.StackTrace);
- }
- return result;
- }
- /// <summary>Serialize object to xml dom</summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static XmlDocument SerializeObjectToXmlDom(object obj)
- {
- XmlDocument xmlDoc = new XmlDocument();
- try
- {
- // 创建 XmlSerializer 用于序列化对象
- XmlSerializer serializer = new XmlSerializer(obj.GetType());
- // 使用 StringWriter 将序列化后的对象写入 XmlWriter
- using (StringWriter stringWriter = new StringWriter())
- {
- using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
- {
- serializer.Serialize(xmlWriter, obj);
- xmlDoc.LoadXml(stringWriter.ToString());
- }
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to serialize object to XML: " + ex.StackTrace);
- }
- return xmlDoc;
- }
- /// <summary>Serialize object to json string</summary>
- /// <returns></returns>
- public static string SerializeObjectToJsonString(object obj)
- {
- string jsonString = "";
- try
- {
- // Serialize the object to a JSON string
- jsonString = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
- return jsonString;
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to serialize object to JSON string. " + ex.StackTrace);
- }
- return jsonString;
- }
- public static string SerializeDataTableToGZipString(DataTable dataTable)
- {
- string result = "";
- try
- {
- // 将 DataTable 序列化为 XML 字符串
- StringWriter stringWriter = new StringWriter();
- dataTable.WriteXml(stringWriter);
- string xmlString = stringWriter.ToString();
- // 将 XML 字符串压缩为 Gzip 格式
- byte[] xmlBytes = Encoding.UTF8.GetBytes(xmlString);
- using (MemoryStream memoryStream = new MemoryStream())
- {
- using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress))
- {
- gzipStream.Write(xmlBytes, 0, xmlBytes.Length);
- }
- result = Convert.ToBase64String(memoryStream.ToArray());
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to serialize DataTable to GZip string: " + ex.StackTrace);
- }
- return result;
- }
- public static DataTable DeserializeDataTableFromGZipString(string gZipString)
- {
- try
- {
- byte[] compressedData = Convert.FromBase64String(gZipString);
- using (MemoryStream memoryStream = new MemoryStream(compressedData))
- {
- using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
- {
- using (StreamReader reader = new StreamReader(gZipStream, Encoding.UTF8))
- {
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataTable));
- return (DataTable)xmlSerializer.Deserialize(reader);
- }
- }
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize DataTable from GZip string: " + ex.StackTrace);
- }
- return null;
- }
- public static string SerializeObjectToGzipString(object obj)
- {
- try
- {
- using (MemoryStream memoryStream = new MemoryStream())
- {
- // 使用 BinaryFormatter 进行对象序列化
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(memoryStream, obj);
- memoryStream.Seek(0, SeekOrigin.Begin);
- // 使用 Gzip 进行压缩
- using (MemoryStream compressedStream = new MemoryStream())
- {
- using (GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Compress))
- {
- memoryStream.CopyTo(gzipStream);
- }
- // 将压缩后的数据转换为 Base64 字符串
- byte[] compressedBytes = compressedStream.ToArray();
- string compressedBase64String = Convert.ToBase64String(compressedBytes);
- return compressedBase64String;
- }
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to serialize object to GZip string: " + ex.StackTrace);
- }
- return "";
- }
- public static T DeserializeObjectFromGzipString<T>(string rawString)
- {
- try
- {
- // Convert the Base64 string back to a byte array
- byte[] compressedData = Convert.FromBase64String(rawString);
- // Decompress the byte array using GZipStream
- using (MemoryStream memoryStream = new MemoryStream(compressedData))
- using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
- using (StreamReader reader = new StreamReader(gZipStream, Encoding.UTF8))
- {
- // Deserialize the XML data to the specified type
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- return (T)xmlSerializer.Deserialize(reader);
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize object from GZip string: " + ex.StackTrace);
- }
- return default(T);
- }
- public static T DeserializeObjectFromJsonString<T>(string jsonString)
- {
- try
- {
- T result = JsonConvert.DeserializeObject<T>(jsonString);
- return result;
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize object from JSON string. " + ex.StackTrace);
- }
- return default(T);
- }
- /// <summary>Serialize object to a xml file</summary>
- /// <param name="fileFullPath"></param>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static void SerializeObjectToXmlFile(string fileFullPath, object obj)
- {
- try
- {
- XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
- // Ensure the directory exists
- string directory = Path.GetDirectoryName(fileFullPath);
- if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
- // Serialize the object to the specified file
- using (StreamWriter writer = new StreamWriter(fileFullPath))
- {
- xmlSerializer.Serialize(writer, obj);
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to serialize object to Xml File: " + ex.StackTrace);
- }
- }
- /// <summary>Deserialize xml stream to object</summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="xmlStream"></param>
- /// <returns></returns>
- public static T DeserializeObjectFromXmlStream<T>(Stream xmlStream)
- {
- try
- {
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- return (T)xmlSerializer.Deserialize(xmlStream);
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize object fromXml stream: " + ex.StackTrace);
- }
- return default(T);
- }
- /// <summary>Deserialize json file to object</summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="fileFullPath"></param>
- /// <returns></returns>
- public static void SerializeObjectToJsonFile<T>(string fileFullPath, object obj)
- {
- try
- {
- // Ensure the directory exists
- string directory = Path.GetDirectoryName(fileFullPath);
- if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
- // Serialize the object to a JSON string
- string jsonString = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
- // Write the JSON string to the file
- File.WriteAllText(fileFullPath, jsonString);
- Console.WriteLine("Object has been serialized and saved to JSON file.");
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to serialize object to JSON file. " + ex.StackTrace);
- }
- }
- /// <summary>Deserialize json file to object</summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="fileFullPath"></param>
- /// <returns></returns>
- public static T DeserializeObjectFromJsonFile<T>(string fileFullPath)
- {
- if (!File.Exists(fileFullPath))
- {
- throw new FileNotFoundException("The specified file was not found.", fileFullPath);
- }
- try
- {
- string jsonContent = File.ReadAllText(fileFullPath);
- T obj = JsonConvert.DeserializeObject<T>(jsonContent);
- return obj;
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize object from JSON file. " + ex.StackTrace);
- }
- return default(T);
- }
- /// <summary>Deserialize xml string to object</summary>
- /// <param name="xmlString"></param>
- /// <param name="objType"></param>
- /// <returns></returns>
- public static object DeserializeObjectFromXmlString(string xmlString, Type objType)
- {
- try
- {
- XmlSerializer serializer = new XmlSerializer(objType);
- using (StringReader stringReader = new StringReader(xmlString))
- {
- return serializer.Deserialize(stringReader);
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize object from xml string. " + ex.StackTrace);
- }
- return null;
- }
- public static T DeserializeObjectFromXmlString<T>(string xmlString)
- {
- try
- {
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- using (StringReader stringReader = new StringReader(xmlString))
- {
- return (T)serializer.Deserialize(stringReader);
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize object from xml string. " + ex.StackTrace);
- }
- return default(T);
- }
- /// <summary>Deserialize xml stream to object</summary>
- /// <param name="xmlStream"></param>
- /// <param name="objType"></param>
- /// <returns></returns>
- public static object DeserializeObjectFromXmlStream(Stream xmlStream, Type objType)
- {
- try
- {
- XmlSerializer serializer = new XmlSerializer(objType);
- return serializer.Deserialize(xmlStream);
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize object from xml stream. " + ex.StackTrace);
- }
- return null;
- }
- /// <summary>Deserialize xml file to object</summary>
- /// <param name="xmlFileFullPath"></param>
- /// <param name="objType"></param>
- /// <returns></returns>
- public static object DeserializeObjectFromXmlFile(string xmlFileFullPath, Type objType)
- {
- if (!File.Exists(xmlFileFullPath))
- {
- throw new FileNotFoundException("XML file not found.", xmlFileFullPath);
- }
- try
- {
- using (FileStream xmlStream = new FileStream(xmlFileFullPath, FileMode.Open))
- {
- XmlSerializer serializer = new XmlSerializer(objType);
- return serializer.Deserialize(xmlStream);
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize object from xml file. " + ex.StackTrace);
- }
- return null;
- }
- /// <summary>Deserialize xml file to object</summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="xmlFileFullPath"></param>
- /// <returns></returns>
- public static T DeserializeObjectFromXmlFile<T>(string xmlFileFullPath)
- {
- if (!File.Exists(xmlFileFullPath))
- {
- throw new FileNotFoundException("XML file not found.", xmlFileFullPath);
- }
- try
- {
- using (FileStream xmlStream = new FileStream(xmlFileFullPath, FileMode.Open))
- {
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- return (T)serializer.Deserialize(xmlStream);
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to deserialize object from xml file. " + ex.StackTrace);
- }
- return default(T);
- }
- /// <summary>Clone object in xml object</summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static object CloneObjectInXml(object obj)
- {
- try
- {
- // Get the type of the object
- Type objType = obj.GetType();
- // Serialize the object to XML
- using (MemoryStream memoryStream = new MemoryStream())
- {
- XmlSerializer serializer = new XmlSerializer(objType);
- serializer.Serialize(memoryStream, obj);
- // Reset the memory stream position to the beginning
- memoryStream.Position = 0;
- // Deserialize the object from the XML
- return serializer.Deserialize(memoryStream);
- }
- }
- catch (Exception ex)
- {
- LOG.Error($"Failed to clone object of type {obj.GetType().Name}." + ex.StackTrace);
- }
- return null;
- }
- /// <summary>Clone object in xml object</summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static T CloneObjectInXml<T>(object obj)
- {
- try
- {
- // Get the type of the object
- Type objType = obj.GetType();
- // Serialize the object to XML
- using (MemoryStream memoryStream = new MemoryStream())
- {
- XmlSerializer serializer = new XmlSerializer(objType);
- serializer.Serialize(memoryStream, obj);
- // Reset the memory stream position to the beginning
- memoryStream.Position = 0;
- // Deserialize the object from the XML
- return (T)serializer.Deserialize(memoryStream);
- }
- }
- catch (Exception ex)
- {
- LOG.Error($"Failed to clone object of type {obj.GetType().Name}." + ex.StackTrace);
- }
- return default(T);
- }
- /// <summary>Serialized a specified typed object into byte array</summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="object1"></param>
- /// <returns></returns>
- public static byte[] SerializeValueType<T>(T object1) where T : struct
- {
- try
- {
- using (MemoryStream memoryStream = new MemoryStream())
- {
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(memoryStream, object1);
- return memoryStream.ToArray();
- }
- }
- catch (Exception ex)
- {
- LOG.Error($"Failed to serialize object of type {typeof(T).Name}." + ex.StackTrace);
- }
- return default(byte[]);
- }
- /// <summary>将传入字符串以GZip算法压缩后,返回Base64编码字符</summary>
- /// <param name="rawString">需要压缩的字符串</param>
- /// <returns>压缩后的Base64编码的字符串</returns>
- public static string GZipCompressString(string rawString)
- {
- try
- {
- byte[] rawData = Encoding.UTF8.GetBytes(rawString);
- using (MemoryStream compressedStream = new MemoryStream())
- {
- using (GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Compress))
- {
- gzipStream.Write(rawData, 0, rawData.Length);
- }
- // Get the compressed data from the memory stream and convert it to a base64 string
- return Convert.ToBase64String(compressedStream.ToArray());
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to compress string using GZip." + ex.StackTrace);
- }
- return "";
- }
- /// <summary>将传入的二进制字符串资料以GZip算法解压缩</summary>
- /// <param name="zippedString">经GZip压缩后的二进制字符串</param>
- /// <returns>原始未压缩字符串</returns>
- public static string GZipDecompressString(string zippedString)
- {
- try
- {
- // Decode the base64 string to get the compressed byte array
- byte[] compressedData = Convert.FromBase64String(zippedString);
- using (MemoryStream compressedStream = new MemoryStream(compressedData))
- {
- using (GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
- {
- using (StreamReader reader = new StreamReader(gzipStream, Encoding.UTF8))
- {
- // Read the decompressed string from the stream
- return reader.ReadToEnd();
- }
- }
- }
- }
- catch (Exception ex)
- {
- LOG.Error("Failed to decompress string using GZip." + ex.StackTrace);
- }
- return "";
- }
- }
- }
|