Object Serialization and Deserialzation in c#

Previously I have written about how to serialize an object to XML. This post is an improved version of that post with better code and the addition of a deserialize example.
Required Namespace to be imported for serialization is System.Xml.Serialization.

This example is also available as a gist

public class Person
{
    public string Name {get; set;}
    public int Age {get;set;}
    public Address Address{get;set;}
}

public class Address
{
    public string Address1 {get;set;}
    public string Town {get;set;}
    public string PostCode{get;set;}
}

void Main()
{
    var p = new Person{
        Name = "John Jones",
        Age = 40,
        Address = new Address{
        Address1= "Daisy Meadow",
        Town="Chorville",
        PostCode = "CH1 1HC"
    }
};
	
XmlSerializer xmlSerializer = new XmlSerializer(p.GetType());
	
var xmlText = string.Empty;
using (TextWriter textWriter = new StringWriter()){
    xmlSerializer.Serialize(textWriter, p);
    xmlText = textWriter.ToString();
}

XmlReaderSettings settings = new XmlReaderSettings();
using(StringReader textReader = new StringReader(xmlText)) {
    using(XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
         ((Person)xmlSerializer.Deserialize(xmlReader)).Dump();
        }
    }
}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.