Persisting and restoring serializable objects using binary, XML and JSON serialization in .NET
Object serialization in .NET allows objects to be stored in persistent storage and later retrieved in their original form. To serialize an object, its class must be marked [Serializable]
. This annotation is crucial when using binary serialization, but is not required with XML or JSON serialization.
The following are examples of functions for binary, XML and JSON serialization:
Binary serialization:
<code class="language-csharp">public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false) { using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create)) { var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); binaryFormatter.Serialize(stream, objectToWrite); } } public static T ReadFromBinaryFile<T>(string filePath) { using (Stream stream = File.Open(filePath, FileMode.Open)) { var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); return (T)binaryFormatter.Deserialize(stream); } }</code>
XML serialization:
<code class="language-csharp">public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new() { TextWriter writer = null; try { var serializer = new XmlSerializer(typeof(T)); writer = new StreamWriter(filePath, append); serializer.Serialize(writer, objectToWrite); } finally { if (writer != null) writer.Close(); } } public static T ReadFromXmlFile<T>(string filePath) where T : new() { TextReader reader = null; try { var serializer = new XmlSerializer(typeof(T)); reader = new StreamReader(filePath); return (T)serializer.Deserialize(reader); } finally { if (reader != null) reader.Close(); } }</code>
JSON serialization (requires Newtonsoft.Json NuGet package):
<code class="language-csharp">public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new() { TextWriter writer = null; try { var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite); writer = new StreamWriter(filePath, append); writer.Write(contentsToWriteToFile); } finally { if (writer != null) writer.Close(); } } public static T ReadFromJsonFile<T>(string filePath) where T : new() { TextReader reader = null; try { reader = new StreamReader(filePath); var fileContents = reader.ReadToEnd(); return JsonConvert.DeserializeObject<T>(fileContents); } finally { if (reader != null) reader.Close(); } }</code>
Usage example:
<code class="language-csharp">// 将someClass变量的内容写入文件。 WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1); // 将文件内容读回变量。 SomeClass object1 = ReadFromBinaryFile<SomeClass>("C:\someClass.txt");</code>
The above is the detailed content of How to Persist and Restore Serializable Objects in .NET Using Binary, XML, and JSON Serialization?. For more information, please follow other related articles on the PHP Chinese website!