Home > Backend Development > C++ > How to Persist and Restore Serializable Objects in .NET Using Binary, XML, and JSON Serialization?

How to Persist and Restore Serializable Objects in .NET Using Binary, XML, and JSON Serialization?

Barbara Streisand
Release: 2025-01-23 11:47:12
Original
320 people have browsed it

How to Persist and Restore Serializable Objects in .NET Using Binary, XML, and JSON Serialization?

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>
Copy after login

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>
Copy after login

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>
Copy after login

Usage example:

<code class="language-csharp">// 将someClass变量的内容写入文件。
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);

// 将文件内容读回变量。
SomeClass object1 = ReadFromBinaryFile<SomeClass>("C:\someClass.txt");</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template