C# Class to Serialize and Deserialize Objects in XML and JSON for any ASP.NET project

Classe ASP.NET C# per il controllo e il calcolo formale del Codice Fiscale

Today we're sharing a small helper which we built some years ago and yet we're still using to handle most serialization/deserialization tasks within any of our ASP.NET active projects. The supported formats are XML and JSON, simply because we never needed anything else other than these two, but it can be easily extended to support anything else.

As you can see we're talking about a simple static class filled with multiple "pairs" of related methods: the former one will serialize any object of type T  into a string, while the latter will deserialize it from the corresponding format. It's worth noting that the serialize methods can also be used as extension methods, assuming the class namespace is properly referenced wherever we want to use it. The class can be used as part of any C# class library or directly included in any Web Forms, Windows Forms, MVC, WebAPI, .NET Core or any other C#-based project type.

Here's a brief list of the methods included within the class:

  • SerializeObject / DeserializeObject
  • SerializeObjectUsingBinaryFormatter / DeserializeObjectUsingBinaryFormatter
  • SerializeToXML / DeserializeFromXML
  • SerializeToJson / DeserializeFromJson

Needless to say, in order for the Serialize method to properly work, the target object must be  [Serializable] , as well as all of its properties.

That's it for now: happy (de)serialization!

 

About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

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