Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

C# – Generic Serialization Methods

DZone's Guide to

C# – Generic Serialization Methods

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, brought to you in partnership with Qlik.

Short blog post today.  These are a couple of generic serialize and deserialize methods that can be easily used when needing to serialize and deserialize classes.  The methods work with any .Net type.  That includes built-in .Net types and custom classes that you might create yourself.

These methods will only serialize PUBLIC properties of a class.  Also, the XML will be human-readable instead of one long line of text.

Serialize Method

/// <summary>
 /// Serializes the data in the object to the designated file path
 /// </summary>
 /// <typeparam name="T">Type of Object to serialize</typeparam>
 /// <param name="dataToSerialize">Object to serialize</param>
 /// <param name="filePath">FilePath for the XML file</param>
 public static void Serialize<T>(T dataToSerialize, string filePath)
 {
      try
      {
           using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
           {
                 XmlSerializer serializer = new XmlSerializer(typeof(T));
                 XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
                 writer.Formatting = Formatting.Indented;
                 serializer.Serialize(writer, dataToSerialize);
                 writer.Close();
           }
      }
      catch
      {
           throw;
      }
 }

Deserialize Method

/// <summary>
 /// Deserializes the data in the XML file into an object
 /// </summary>
 /// <typeparam name="T">Type of object to deserialize</typeparam>
 /// <param name="filePath">FilePath to XML file</param>
 /// <returns>Object containing deserialized data</returns>
 public static T Deserialize<T>(string filePath)
 {
      try
      {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T serializedData;

            using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                 serializedData = (T)serializer.Deserialize(stream);
            }

            return serializedData;
      }
      catch
      {
            throw;
      }
 }

Here is some sample code to show the methods in action.

Person p = new Person() { Name = "John Doe", Age = 42 };
XmlHelper.Serialize<Person>(p, @"D:\text.xml");

Person p2 = new Person();
p2 = XmlHelper.Deserialize<Person>(@"D:\text.xml");

Console.WriteLine("Name: {0}", p2.Name);
Console.WriteLine("Age: {0}", p2.Age);

Console.Read();

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:
dotnet ,tips and tricks ,.net & windows ,c-sharp

Published at DZone with permission of Ryan Alford, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}