A serialization helper class with Generic.
1

/**//// <summary>2
/// A serialization helper class.3
/// </summary>4
public static class SerializationHelper5

{6

/**//// <summary>7
/// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.8
/// </summary>9
/// <param name="characters">Unicode Byte Array to be converted to String</param>10
/// <returns>String converted from Unicode Byte Array</returns>11
private static string UTF8ByteArrayToString(byte[] characters)12

{13
UTF8Encoding encoding = new UTF8Encoding();14
string constructedString = encoding.GetString(characters);15
return (constructedString);16
}17

18

/**//// <summary>19
/// Converts the String to UTF8 Byte array and is used in De serialization20
/// </summary>21
/// <param name="pXmlString"></param>22
/// <returns></returns>23
private static Byte[] StringToUTF8ByteArray(string pXmlString)24

{25
UTF8Encoding encoding = new UTF8Encoding();26
byte[] byteArray = encoding.GetBytes(pXmlString);27
return byteArray;28
}29

30

/**//// <summary>31
/// Serialize an object into an XML string32
/// </summary>33
/// <typeparam name="T"></typeparam>34
/// <param name="obj"></param>35
/// <returns></returns>36
public static void SerializeObject<T>(T obj, string filePath)37

{38
using (FileStream fs = new FileStream(filePath, FileMode.Create))39

{40
41
MemoryStream stream = new MemoryStream();42
XmlSerializer xs = new XmlSerializer(typeof(T));43
XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.UTF8);44
xs.Serialize(xmlTextWriter, obj);45
stream = (MemoryStream)xmlTextWriter.BaseStream;46
byte[] buffer = stream.ToArray();47
fs.Write(buffer, 0, buffer.Length);48
fs.Flush();49
}50
51
}52

53

/**//// <summary>54
/// Reconstruct an object from an XML string55
/// </summary>56
/// <param name="xml"></param>57
/// <returns></returns>58
public static T DeserializeObject<T>(string xml)59

{60
byte[] buffer = null;61

62
using (FileStream fs = new FileStream(xml, FileMode.Open))63

{64
buffer = new byte[fs.Length];65
fs.Read(buffer, 0, buffer.Length);66
67
}68
using (MemoryStream stream = new MemoryStream(buffer))69

{70
XmlSerializer ser = new XmlSerializer(typeof(T));71
return (T)ser.Deserialize(stream);72
}73
74
75
}76
private static T DeserializeXml<T>(T instance, byte[] buffer)77

{78
using (MemoryStream stream = new MemoryStream(buffer))79

{80
XmlSerializer ser = new XmlSerializer(typeof(T));81
instance = (T)ser.Deserialize(stream);82
return instance;83
}84
}85

86

87
}88

浙公网安备 33010602011771号