Serialization enables us to store or transmit data structures or objects. This can be done by converting the data to a textual representation when storing or transmitting them which also allows us to recreate the original object using the stored information.
Lets create a dummy class called Person, that will hold some basic information.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public int ID { get; set; }
private Person()
{
}
public Person(string name, string surname, int id)
{
this.Name = name;
this.Surname = surname;
this.ID = id;
}
}
|
Keep in mind that your class needs to have a parameterless constructor in order to be serialized or else you will get an InvalidOperationException
exception (cannot be serialized because it does not have a parameterless constructor) if you try to serialize a class without one. Luckily you can just set it to private or internal so it won’t be accessible from other classes.
Now it is time to serialize our Person object.
|
Person aPerson = new Person("name", "surname", 1); // The Person object which we will serialize
string serializedData = string.Empty; // The string variable that will hold the serialized data
XmlSerializer serializer = new XmlSerializer(aPerson.GetType());
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, aPerson);
serializedData = sw.ToString();
}
|
At this point our serializedData
variable will be holding the serialized data. This is what you will use when storing or transmitting your object somewhere. You can see below the contents of serializedData
.
|
<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>name</Name>
<Surname>surname</Surname>
<ID>1</ID>
</Person>
|
Now lets deserialize our data to recreate our Person object.
|
XmlSerializer deserializer = new XmlSerializer(typeof(Person));
using (TextReader tr = new StringReader(serializedData))
{
Person deserializedPerson = (Person)deserializer.Deserialize(tr);
}
|
The deserializedPerson
object will have exactly the same data as the object we serialized at the start.
Hopefully the above example helped you understand the basics on how to serialize and deserialize objects. If you have any questions feel free to ask in the comments below.
from : https://www.fluxbytes.com/csharp/serialize-an-object-to-string-and-from-string-back-to-object/