Posts

Showing posts from June, 2023

Donate

BinaryFormatter Custom Binder Alternative Using Newtonsoft.Json.JsonSerializer In C#

Hello Everyone! In relation to the previous post on updating the serialization and deserialization using BinaryFormatter class to NewtonSoft's JsonSerializer, we also need to change the Binder functionality using NewtonSoft. The class below inherits the SerializationBinder and overrides the BindToType() function. sealed class HELPERSCustomBinder : SerializationBinder { public override Type BindToType( string assemblyName, string typeName) { if (!typeName.ToUpper().Contains( "SYSTEM.STRING" )) { throw new SerializationException( "Only List<string> is allowed" ); } return Assembly.Load(assemblyName).GetType(typeName); } } The class above will then be assigned to the Binder property of BinaryFormatter as shown from the code snippet below. public static T BuildFromSerializedBuffer<T>( byte [] buffer) where T : new () { MemoryStream MS; BinaryFormatter BF; T rtn; rtn = default (T); try { using (M

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 ser

Donate