DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • New ORM Framework for Kotlin
  • TopicRecordNameStrategy in Kafka
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts

Trending

  • OneStream Fast Data Extracts APIs
  • How To Use ChatGPT API in Python for Your Real-Time Data
  • Monkey-Patching in Java
  • API Design
  1. DZone
  2. Data Engineering
  3. Data
  4. C# – Generic Serialization Methods

C# – Generic Serialization Methods

Ryan Alford user avatar by
Ryan Alford
·
Jun. 24, 12 · Tutorial
Like (0)
Save
Tweet
Share
26.87K Views

Join the DZone community and get the full member experience.

Join For Free

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();
Serialization POST (HTTP) XML Property (programming) Blog Data Types

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

Opinions expressed by DZone contributors are their own.

Related

  • New ORM Framework for Kotlin
  • TopicRecordNameStrategy in Kafka
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Streamlining Your Workflow With the Jenkins HTTP Request Plugin: A Guide to Replacing CURL in Scripts

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: