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

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

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();

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

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.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}