Home > Backend Development > C++ > How to Serialize and Deserialize Objects in C#?

How to Serialize and Deserialize Objects in C#?

DDD
Release: 2025-01-23 11:42:11
Original
306 people have browsed it

How to Serialize and Deserialize Objects in C#?

Saving and restoring C# objects: serialization and deserialization

Serialization stores data in a portable format, making it easier to transfer objects between different applications, systems, or machines.

To serialize an object, you must use the [Serializable] attribute tag and include a parameterless constructor. Additionally, the [XmlIgnore] and [JsonIgnore] attributes can be used to exclude specific attributes or fields.

Example

Consider the following SomeClass:

[Serializable]
public class SomeClass
{
    public string someProperty { get; set; }
}

SomeClass object1 = new SomeClass { someProperty = "someString" };
Copy after login

Save to file

  • BinarySerialization:

      BinaryFormatter binaryFormatter = new BinaryFormatter();
    
      using (Stream stream = File.Create("object1.bin"))
      {
          binaryFormatter.Serialize(stream, object1);
      }
    Copy after login
  • XML Serialization:

      XmlSerializer serializer = new XmlSerializer(typeof(SomeClass));
    
      using (TextWriter writer = new StreamWriter("object1.xml"))
      {
          serializer.Serialize(writer, object1);
      }
    Copy after login
  • JSONSerialization:

      using (StreamWriter writer = new StreamWriter("object1.json"))
      {
          writer.Write(JsonConvert.SerializeObject(object1));
      }
    Copy after login

Recover from Files

  • BinaryDeserialization:

      BinaryFormatter binaryFormatter = new BinaryFormatter();
    
      using (Stream stream = File.OpenRead("object1.bin"))
      {
          object1 = (SomeClass)binaryFormatter.Deserialize(stream);
      }
    Copy after login
  • XML Deserialization:

      XmlSerializer serializer = new XmlSerializer(typeof(SomeClass));
    
      using (TextReader reader = new StreamReader("object1.xml"))
      {
          object1 = (SomeClass)serializer.Deserialize(reader);
      }
    Copy after login
  • JSON Deserialization (JsonDeserialization):

      using (StreamReader reader = new StreamReader("object1.json"))
      {
          object1 = JsonConvert.DeserializeObject<SomeClass>(reader.ReadToEnd());
      }
    Copy after login

    The above is the detailed content of How to Serialize and Deserialize Objects in C#?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template