Click here to Skip to main content
16,004,564 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Experts,

We have used binary format serialization/deserialization in our application.
Its C# desktop application targeting .Net FW 4.6

// Convert an object to a byte array
        public static byte[] ObjectToByteArray(Object obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (var ms = new MemoryStream())
            {
                bf.Serialize(ms, obj);
                return ms.ToArray();
            }
        }


// Convert a byte array to an Object : Old implementation
        public static Object ByteArrayToObject(byte[] arrBytes)
        {
            using (var memStream = new MemoryStream())
            {
                var binForm = new BinaryFormatter
                {
                    Binder = new SerializationBinder()
                };

                // Deserialization 
                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.
Posted
Updated 11-Jun-24 18:25pm
v3
Comments
Richard Deeming 12-Jun-24 3:51am    
NB: You can replace:
byteArray == null || !byteArray.Any()

with:
byteArray is null or []

You cannot use JSON deserialization on binary serialized data.

You must deserialize the data using the binary formatter to reconstitute the data back into your app objects.

Once you have the objects, you can serialize them using the JSON formatter so you can store the serialized data in whatever storage you were using. JSON is just text, so it's going to be human readable.
 
Share this answer
 
Comments
CPallini 12-Jun-24 4:22am    
5.
Maciej Los 17-Jun-24 14:44pm    
5ed!
charles henington 4-Jul-24 21:02pm    
What are your thoughts on making Json non human readable? If you had to choose between using a GZipStream or Encryption, which would you choose and why?
Dave Kreskowiak 4-Jul-24 21:39pm    
Increases time to process. You have to serialize to JSON, compress it, send it, on and the receiving end, decompress it, then deserialize. I see no real benefit.

From the OP's question, it seems like he was trying to use a JSON deserializer on a binary stream, which obviously will not work.
Could you not just use JsonSerializer.Serialize(Stream, obj); and JsonSerializer.Deseralize(Stream) instead?

Here is an example of such on a very basic class.

C#
[Serializable, StructLayout(LayoutKind.Sequential)]
public class RgbClass(byte r, byte g, byte b)
{
    private readonly byte r = r;
    private readonly byte g = g; 
    private readonly byte b = b;

    public byte R => r;
    public byte B => b;
    public byte G => g;

    public static RgbClass? Load(byte[] array)
    {
        using MemoryStream ms = new(array);
        return (RgbClass?)JsonSerializer.Deserialize<RgbClass?>(ms);
    }
    public byte[] GetBytes()
    {
        using MemoryStream ms = new();
        JsonSerializer.Serialize(ms, this);
        return ms.ToArray();
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900