Tuesday, January 19, 2010

Code: Serializing and Deserializing Objects (Converting Objects to a String and Back)

Object serialization in .Net is pretty easy, once you have the right code.  It took me a few minutes to figure out the right code so I thought I’d post it here.  The code below is a working C# console app.

Code Snippet
  1. using System;
  2. using System.IO;
  3. using System.Xml.Serialization;
  4.  
  5. namespace TestApp
  6. {
  7.     public class Program
  8.     {
  9.         static string serializedObject;
  10.  
  11.         static void Main(string[] args)
  12.         {
  13.             Serialize();
  14.             Deserialize();
  15.         }
  16.  
  17.         static void Serialize()
  18.         {
  19.             Person p = new Person() { Age = 20, Name = "Bob" };
  20.             XmlSerializer serializer = new XmlSerializer(p.GetType());
  21.             using (StringWriter sw = new StringWriter())
  22.             {
  23.                 serializer.Serialize(sw, p);
  24.                 serializedObject = sw.GetStringBuilder().ToString();
  25.             }
  26.         }
  27.  
  28.         static void Deserialize()
  29.         {
  30.             XmlSerializer serializer = new XmlSerializer(typeof(Person));
  31.             Person p = (Person)serializer.Deserialize(new StringReader(serializedObject));
  32.             Console.WriteLine("Name:" + p.Name + " Age:" + p.Age);
  33.             Console.ReadLine();
  34.         }
  35.  
  36.         public class Person
  37.         {
  38.             public int Age { get; set; }
  39.             public string Name { get; set; }
  40.         }
  41.     }
  42. }