Hi Experts,
We have used binary format serialization/deserialization in our application.
Its C# desktop application targeting .Net FW 4.6
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
public static Object ByteArrayToObject(byte[] arrBytes)
{
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter
{
Binder = new SerializationBinder()
};
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = binForm.Deserialize(memStream);
return obj;
}
}
But recently Binary format becomes obsolete and recommends to use other methods like json serialization.
We have tried this JSON method
Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(obj, GetJsonSerializerOptions()));
public static T ByteArrayToObject<T>(byte[] byteArray)
{
if (byteArray == null || !byteArray.Any())
return default;
return System.Text.Json.JsonSerializer.Deserialize<T>(byteArray, GetJsonSerializerOptions());
}
But the issue is the binary to json deserialization is causing invalid format exception. Is there anything missing from my side, please advise.
What I have tried:
We have tried this JSON method
Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(obj, GetJsonSerializerOptions()));
public static T ByteArrayToObject<T>(byte[] byteArray)
{
if (byteArray == null || !byteArray.Any())
return default;
return System.Text.Json.JsonSerializer.Deserialize<T>(byteArray, GetJsonSerializerOptions());
}
private static JsonSerializerOptions GetJsonSerializerOptions()
{
return new JsonSerializerOptions()
{
PropertyNamingPolicy = null,
WriteIndented = true,
AllowTrailingCommas = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
}
But the issue is the binary to json deserialization is causing invalid format exception. Is there anything missing from my side, please advise.