Posts

Showing posts with the label Newtonsoft.Json

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

Unexpected character encountered while parsing value: C. Path '', line 0, position 0. (Deserialize JSON String Error In C#)

Hi, A common issue when deserializing a JSON object in C# is to pass the filepath of the JSON file to the Deserialize() method instead of the string content of that file such as the code below. var obj = JsonConvert.DeserializeObject<Employee>( @"D:\Data\Employee.json" ) When calling the Deserialize() method, you need to make sure that the parameter passed is a JSON string value instead of the file path. Use StreamReader class or File.ReadAllText() to get the content of the JSON file. using (StreamReader reader = new StreamReader( @"D:\Data\Employee.json" )) { string json = reader.ReadToEnd(); var obj = JsonConvert.DeserializeObject<Employee>(json); }

Donate