Site icon Ryadel

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!

 

Exit mobile version