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
{
/// Serialize the supplied object To Xml stream
///
///
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;
}
/// Serialize object to xml dom
///
///
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;
}
/// Serialize object to json string
///
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(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(string jsonString)
{
try
{
T result = JsonConvert.DeserializeObject(jsonString);
return result;
}
catch (Exception ex)
{
LOG.Error("Failed to deserialize object from JSON string. " + ex.StackTrace);
}
return default(T);
}
/// Serialize object to a xml file
///
///
///
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);
}
}
/// Deserialize xml stream to object
///
///
///
public static T DeserializeObjectFromXmlStream(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);
}
/// Deserialize json file to object
///
///
///
public static void SerializeObjectToJsonFile(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);
}
}
/// Deserialize json file to object
///
///
///
public static T DeserializeObjectFromJsonFile(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(jsonContent);
return obj;
}
catch (Exception ex)
{
LOG.Error("Failed to deserialize object from JSON file. " + ex.StackTrace);
}
return default(T);
}
/// Deserialize xml string to object
///
///
///
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(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);
}
/// Deserialize xml stream to object
///
///
///
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;
}
/// Deserialize xml file to object
///
///
///
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;
}
/// Deserialize xml file to object
///
///
///
public static T DeserializeObjectFromXmlFile(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);
}
/// Clone object in xml object
///
///
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;
}
/// Clone object in xml object
///
///
public static T 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 (T)serializer.Deserialize(memoryStream);
}
}
catch (Exception ex)
{
LOG.Error($"Failed to clone object of type {obj.GetType().Name}." + ex.StackTrace);
}
return default(T);
}
/// Serialized a specified typed object into byte array
///
///
///
public static byte[] SerializeValueType(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[]);
}
/// 将传入字符串以GZip算法压缩后,返回Base64编码字符
/// 需要压缩的字符串
/// 压缩后的Base64编码的字符串
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 "";
}
/// 将传入的二进制字符串资料以GZip算法解压缩
/// 经GZip压缩后的二进制字符串
/// 原始未压缩字符串
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 "";
}
}
}