Donate

BinaryFormatter Serialize() And Deserialize() Alternative Using Newtonsoft.Json.JsonSerializer In C#

Good evening!

Part of the migration of our parts cataloging WPF application to .NET 7 was to investigate obsolete code and refactor that to something acceptable and maintainable in the future. One of which that needs to be addressed is the BinaryFormatter class used for serialization and deserialization. Searching thru the internet presents tons of options but since the application has already a Newtonsoft.Json package, we decided to use it's serialization instead. So to proceed with, below are the sample serialization and deserialization functions that incorporates the BinaryFormatter class and converted to NewtonSoft.Json.JsonSerializer. Below is a function using BinaryFormatter serialization.
public static byte[] GetSerializedBuffer<T>(T itemToSerialize)
{
	 byte[] rtn;
	 MemoryStream MS;
	 BinaryFormatter BF;

	 if (!typeof(T).IsSerializable && !(typeof(ISerializable).IsAssignableFrom(typeof(T))))
		throw new InvalidOperationException("A serializable Type is required");

	 rtn = null;
	 try
	 {
		using (MS = new MemoryStream())
		{
		   BF = new BinaryFormatter();
		   BF.Serialize(MS, itemToSerialize);
		   rtn = MS.ToArray();
		}
	 }
	 catch
	 {
		
	 }

	 return rtn;
}
The method below is the revised version of the code above that implements the serialization approach using NewtonSoft.Json.JsonSerializer, StreamWriter and JsonTextWriter classes.
public static byte[] GetSerializedBuffer<T>(T itemToSerialize)
{
	 byte[] rtn;
	 MemoryStream MS;

	 if (!typeof(T).IsSerializable && !(typeof(ISerializable).IsAssignableFrom(typeof(T))))
		throw new InvalidOperationException("A serializable Type is required");

	 rtn = null;
	 try
	 {
		using (MS = new MemoryStream())
		{
		   Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
		   using (var sw = new StreamWriter(MS))
		   {
			  using (JsonWriter writer = new JsonTextWriter(sw))
			  {
				 serializer.Serialize(writer, itemToSerialize);
			  }
		   }
		   rtn = MS.ToArray();
		}
	 }
	 catch
	 {
		
	 }

	 return rtn;
}
This method applies the BinaryFormatter deserialization method to deserialize the stream object into a complex type object.
public static clsUserSettings GetUserSettings()
{
	 clsUserSettings Settings;
	 IFormatter formatter;
	 Stream stream;

	 Settings = new clsUserSettings();
	 formatter = new BinaryFormatter();

	 string settingPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "CebuPacific", "PartsInventory");
	 string settingFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "CebuPacific", "PartsInventory", "UserSettings.txt");
	 if (Directory.Exists(settingPath))
	 {
		if (File.Exists(settingFile))
		{
		   stream = new FileStream(settingFile, FileMode.Open, FileAccess.Read);
		   Settings = (clsUserSettings)formatter.Deserialize(stream);
		   stream.Close();
		   stream.Dispose();
		}
	 }

	 if (Settings.Settings.Where(x => x.Contract == clsDBSetting.Instance.SelectedContractName).Count() == 0)
		Settings.Settings.Add(new clsContractSettings { Contract = clsDBSetting.Instance.SelectedContractName, CustomDataGridOrder = new List<clsDataGridColumnOrder>() });

	 return Settings;
}
The function below, changed the BinaryFormatter deserialization into a NewtonSoft approach using JsonSerializer, StreamReader and JsonTextReader classes.
public static clsUserSettings GetUserSettings()
{
 clsUserSettings Settings;
 Stream stream;

 Settings = new clsUserSettings();

 string settingPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "CebuPacific", "PartsInventory");
 string settingFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "CebuPacific", "PartsInventory", "UserSettings.txt");
 if (Directory.Exists(settingPath))
 {
	if (File.Exists(settingFile))
	{
	   stream = new FileStream(settingFile, FileMode.Open, FileAccess.Read);
	   var serializer = new Newtonsoft.Json.JsonSerializer();
	   using (var sr = new StreamReader(stream))
	   using (var jsonTextReader = new JsonTextReader(sr))
	   {
		  Settings = serializer.Deserialize<clsUserSettings>(jsonTextReader);
	   }
	}
 }

 if (Settings.Settings.Where(x => x.Contract == clsDBSetting.Instance.SelectedContractName).Count() == 0)
	Settings.Settings.Add(new clsContractSettings { Contract = clsDBSetting.Instance.SelectedContractName, CustomDataGridOrder = new List<clsDataGridColumnOrder>() });

 return Settings;
}


Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.