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
:
<code class="language-csharp">[Serializable] public class SomeClass { public string someProperty { get; set; } } SomeClass object1 = new SomeClass { someProperty = "someString" };</code>
Save to file
BinarySerialization:
<code class="language-csharp"> BinaryFormatter binaryFormatter = new BinaryFormatter(); using (Stream stream = File.Create("object1.bin")) { binaryFormatter.Serialize(stream, object1); }</code>
XML Serialization:
<code class="language-csharp"> XmlSerializer serializer = new XmlSerializer(typeof(SomeClass)); using (TextWriter writer = new StreamWriter("object1.xml")) { serializer.Serialize(writer, object1); }</code>
JSONSerialization:
<code class="language-csharp"> using (StreamWriter writer = new StreamWriter("object1.json")) { writer.Write(JsonConvert.SerializeObject(object1)); }</code>
Recover from Files
BinaryDeserialization:
<code class="language-csharp"> BinaryFormatter binaryFormatter = new BinaryFormatter(); using (Stream stream = File.OpenRead("object1.bin")) { object1 = (SomeClass)binaryFormatter.Deserialize(stream); }</code>
XML Deserialization:
<code class="language-csharp"> XmlSerializer serializer = new XmlSerializer(typeof(SomeClass)); using (TextReader reader = new StreamReader("object1.xml")) { object1 = (SomeClass)serializer.Deserialize(reader); }</code>
JSON Deserialization (JsonDeserialization):
<code class="language-csharp"> using (StreamReader reader = new StreamReader("object1.json")) { object1 = JsonConvert.DeserializeObject<SomeClass>(reader.ReadToEnd()); }</code>
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!